# shop.py
from pyppeteer.page import Page
from pyppeteer_stealth import stealth
from playwright_tool import playwright_connect_browser,wait_goto_response
from playwright_tool import check_login as pl_cklogin
from playwright_tool import LoginError
from papi import *
from lxml import etree
from config import *
from county_config import *
from tool import *
from api import *
from sql import sqlseverDB
import requests,concurrent.futures
import math,traceback,logging,inspect
import shutil,string,os

class Shop:

    def __init__(self,basic_info):
        self.basic_info=basic_info
        self.basic_info['PingTai']='shopee'
        self.basic_info['host']=basic_info['Platform']
        self.host=basic_info['Platform']
        self.shopid=basic_info['shopid']
        self.bid=basic_info['BrowserID']
        self.dpName=basic_info['DpName']
        self.userName = basic_info['UserName']
        self.password = basic_info['Password']
        self.yybm=basic_info['YYBM']
        self.gname=basic_info['GroupName']
        self.sjbm=basic_info['SJBM']
        self.shopid=basic_info['shopid']
        self.iskj=basic_info['is_KJ']
        if basic_info['CurrenyRate']:
            basic_info['exchange_rate']=basic_info['CurrenyRate']
        self.session=requests.session()
        self.ck=None
        self.SPC_CDS=None
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)

    async def close_browser(self,bro):
        bid=self.bid
        bname=self.dpName
        task_id=self.task_id
        aff_close=tms.ExecNoQuery('update taskstatus set is_on=0 where bid=? and task_id=?',(bid,task_id))
        rs= tms.ExecQuery('select count(*) from taskstatus where bid=? and task_id!=? and is_on=1',(bid,task_id))
        
        if rs[0][0]==0:
            try:
                await bro.close()
                logging.info(f'店铺:{bname},{bid},关闭浏览器成功,记录状态:{aff_close}')
            except Exception as e:
                logging.error(f'店铺:{bname},{bid},关闭浏览器失败,记录状态:{aff_close}')

        else:
            logging.info(f'店铺:{bname},{bid},有其他 {rs[0][0]} 个任务,正在运行,稍后关闭')

    async def check_login(self,page:Page):
        wait_count=0
        no_login_count=0
        task_id=self.task_id
        task_name=Task_Name_dict[task_id]

        while True:
            now_time_str=datetime.datetime.now()
            zds=['iscl','task_id','task_name','BID','loginTime','pintai','bname','gname','des']
            params=[0,task_id,task_name,self.bid,now_time_str,'shopee',self.dpName,self.gname]
            zd_on=['BID']
            if MAX_WAIT and wait_count>MAX_WAIT:
                err_des='等待时间过长'
                params.append(err_des)
                aff=self.ms.merge_into('ErrBid',zds,params,zd_on)
                logging.info(f'店铺:{self.dpName},bid:{self.bid},{err_des},已登记错误:{aff}')
                await page.close()
                return
            try:
                acc=await page.xpath('//div[@class="subaccount-info"]')
                acc_kj= await page.xpath('//div[@class="account-name"]')
                no_login=await page.xpath('//input[@name="loginKey"]')
                no_login2=await page.xpath('//div[@class="login-frame"]')
                el_ck_phone=await page.xpath('//div[@class="verify-container"]//button/span[text()=" Cancel "]')
                cot= await page.content()
                if 'Halaman Tidak Tersedia' in cot  or 'verify/captcha' in page.url:
                    err_des='登录跳转到失败页面'
                    params.append(err_des)
                    aff=self.ms.merge_into('ErrBid',zds,params,zd_on)
                    logging.info(f'店铺:{self.dpName},bid:{self.bid},{err_des},已登记错误:{aff}')
                    await page.close()
                    return
                
                if "Can't use Marketing centre now.Because your shop is on vacation mode，please toggle off vacation mode first" in cot:
                    logging.info(f'店铺:{self.dpName},bid:{self.bid},处于假期模式退出')
                    await page.close()
                    return
                
                if "ps_cannot_use_marketing_center_of_in_vacation_mode_label" in cot:
                    logging.info(f'店铺:{self.dpName},bid:{self.bid},处于假期模式退出')
                    await page.close()
                    return
                
                if el_ck_phone:
                    #手机验证
                    await el_ck_phone[0].click({'delay':200})
                    await asyncio.sleep(3)

                if no_login or no_login2:
                    if no_login_count>=3:
                        err_des='卡在登录页面'
                        params.append(err_des)
                        aff=self.ms.merge_into('ErrBid',zds,params,zd_on)
                        logging.info(f'店铺:{self.dpName},bid:{self.bid},{err_des},已登记错误:{aff}')
                        await page.close()
                        return
                    logging.info(f'店铺:{self.dpName},账号未登录,进行登录')
                    if not self.userName or not self.password:
                        err_des='没有账号密码'
                        params.append(err_des)
                        aff=self.ms.merge_into('ErrBid',zds,params,zd_on)
                        logging.info(f'店铺:{self.dpName},bid:{self.bid},{err_des},已登记错误:{aff}')
                        await page.close()
                        return
                    await repeat_reload(page)
                    await asyncio.sleep(10)
                    cot=await page.content()
                    el_isusername=etree.HTML(cot).xpath('//input[@name="loginKey"]/@value')
                    haspad=False
                    if el_isusername:
                        cusername=el_isusername[0]
                        if cusername:
                            haspad=True
                    if not haspad:
                        await page.type('input[name=loginKey]',self.userName,{'delay': 120})
                        await page.type('input[name=password]',self.password,{'delay': 120})
                    await page.waitFor(1000)
                    btn_login=(await page.xpath('//form/button[1]'))[0]
                    await btn_login.click()
                    await asyncio.sleep(15)
                    no_login_count+=1
                    
                if acc and self.basic_info['is_KJ']==0:
                    self.ms.ExecNoQuery('update ErrBid set iscl=1 where BID=? and iscl=0',(self.bid,))
                    logging.info(f'店铺:《{self.dpName}》,{self.bid},已登录')
                    return page
                if acc_kj and self.basic_info['is_KJ']==1:
                    logging.info(f'店铺:《{self.dpName}》,{self.bid},已登录')
                    self.ms.ExecNoQuery('update ErrBid set iscl=1 where BID=? and iscl=0',(self.bid,))
                    return page

                wait_count+=1
                    
            except Exception as e:
                logging.info(e)
                wait_count+=1
            await asyncio.sleep(2)
    
    async def yb_get_Homeinfo(self):
        '''采集店铺首页'''
        basic_info=self.basic_info
        host=basic_info['host']
        bid=self.bid
        is_kj=self.iskj
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/'
        if is_kj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}

        await asyncio.sleep(5)
        xpath='//div[@class="todo-title"]'
        if is_kj==1:
            xpath='//div[@class="todo-list-container"]'
        
        await plw_wait_xpath(page,xpath,host)
        zds=[]
        params=[]
        
        shopid=await plw_xp_get_shopid(page,self.basic_info)
        if not shopid:
            await self.close_browser(browser)
            return {'code':-3,'msg':'获取Shopid失败'}

        self.basic_info['shopid']=shopid
        
        if is_kj==1:
            zds,params=await plw_xp_get_kj_homeinfo(page,basic_info)
        else:
            #获取 To Do List 8个参数值
            res_to_do_list=await pwl_get_to_do_list(page,self.basic_info)
            if res_to_do_list:
                zds.extend(['unpaid','to_process_shipment','processed_shipment','pending_cancellation',
                    'pending_return','banned_products','sold_out_products','to_join_bidding'])
                params.extend(res_to_do_list)
            else:
                logging.info(f'店铺:{self.dpName},{self.bid},获取《To Do List》内容失败')

            #获取 Business Insights 8个参数
            res_business_insights=await plw_get_business_insights(page,self.basic_info)
            if res_business_insights:
                zds.extend(['visitors','visitors_trend','page_views','page_views_trend',
                    'orders','orders_trend','conversion_rate','conversion_rate_trend'])
                params.extend(res_business_insights)
            else:
                logging.info(f'店铺:{self.dpName},{self.bid},获取《Business Insights》内容失败')
            
            #获取 Performance 4个参数
            res_performance=await plw_get_performance(page,self.basic_info)
            if res_performance:
                zds.extend(['Non_fulfilment_Rate','Late_Shipment_Rate','Preparation_Time','My_Penalty'])
                params.extend(res_performance)
            else:
                logging.info(f'店铺:{self.dpName},{self.bid},获取《Performance》内容失败')


        #获取广告剩余费用
        ads_credit=await plw_get_ads_credit(page,self.basic_info)
        if ads_credit is not None:
            zds.extend(['ads_credit'])
            params.extend([ads_credit])
        else:
            logging.info(f'店铺:{self.dpName},{self.bid},获取《ads_credit》内容失败')

        
        el_kyc=page.locator('xpath=//div[@class="kyc-text"]')
        kyc=None
        if (await el_kyc.count()>0):
            kyc='异常'
            logging.info(f'店铺:{self.dpName},{self.bid},KYC异常')
        zds.extend(['KYC'])
        params.extend([kyc])

        
        ad_count= await plw_get_camp_info(page,self.basic_info,True)
        zds.append('ad_count')
        params.append(ad_count)
        if not zds:
            logging.info(f'店铺:{self.dpName},{self.bid},获取首页内容失败')
            return {'code':-3,'msg':'获取首页内容失败'}
        else:
            bid=self.bid
            dpname=self.dpName
            yybm=self.yybm
            gname=self.gname
            login_url=f'https://{self.host}/'
            now_time= datetime.datetime.now()
            zds=['SJBM','shopName','YYBM','GroupName','shopid','bid','longinUrl','userName','password']+zds
            params=[self.sjbm,dpname,yybm,gname,shopid,bid,login_url,self.userName,self.password]+params
            params.append(now_time)
            
            rs=self.ms.ExecQuery('select count(*) from ShopHome where shopid=?',(shopid,))
            if rs[0][0]>0:
                zds.append('update_time')
                zdstr=','.join([f'{zd}=?' for zd in zds])
                sqlstr=f'update [ShopHome] set {zdstr} where shopid=?'
                aff=self.ms.ExecNoQuery(sqlstr,params+[shopid])
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':0,'msg':'更新','aff':aff}
            else:
                zds=zds+['update_time','upload_time']
                params.append(now_time)
                zdstr=','.join(zds)
                wstr=','.join(['?' for _ in params])
                sqlstr=f'insert into ShopHome({zdstr}) values({wstr})'
                aff=self.ms.ExecNoQuery(sqlstr,params)
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':0,'msg':'新增','aff':aff}

    async def yb_delete_product2(self):
        '''删除店铺全部产品'''
        browser=await openSunBrowser(self.basic_info,self.task_id)
        if not browser:
            return {'code':-1,'msg':'启动浏览器失败'}
        
        page=await browser.newPage()
        t0=asyncio.create_task(bring_to_front_if_needed(page))
        lastpg=False
        aff=0
        pro_url_path=f'https://{self.host}/portal/product/list'
        pro_lxnames=['/live/all','/reviewing','/unpublished/unlisted','/unpublished/draft']

        for pro_lxname in  pro_lxnames:
            purl=f'{pro_url_path}{pro_lxname}'
            await repeat_goto(page,purl)
            sss=await self.check_login(page)
            if not sss:
                await self.close_browser(browser)
                return {'code':-2,'msg':'账户登录失败'}
            await asyncio.sleep(20)
            await wait_one_xpath(page,'//div[@class="tabs__tab"]')
            cot=await page.content()

            livetxt=etree.HTML(cot).xpath('//div[@class="list-header-title"]/text()')[0]
            allpro_count=int(livetxt.replace('products','').replace('product','').replace('.','').strip())
            logging.info(f'{self.dpName},{self.bid},{pro_lxname},还剩{allpro_count}个产品未删除')
            max_ppp=math.ceil(allpro_count/12)
            if pro_lxname in ['/unpublished/unlisted','/unpublished/draft']:
                max_ppp=math.ceil(allpro_count/20)
            for ppp in range(max_ppp):
                logging.info(f'{self.dpName},{self.bid},{pro_lxname},正在删除第 {ppp+1} 页,共{max_ppp}页')
                await repeat_goto(page,purl)
                
                await asyncio.sleep(5)
                await wait_one_xpath(page,'//div[@class="tabs__tab"]')

                el_tc=await page.xpath('//div[@class="eds-modal__content eds-modal__content--medium"]')
                if el_tc:
                    logging.info(f'出现弹窗...')
                    el_btn_close=await el_tc[0].xpath('.//button[1]')
                    try:
                        await el_btn_close[0].click({'delay':200})
                    except Exception as e:
                        logging.info(e)
                await check_tc(page,'//div[@class="FULMadiY5u"]//div[text()="Maybe Later"]')

                el_ckpro=await wait_one_xpath(page,'//div[@class="eds-table__main-header"]/table[1]/thead[1]/tr[1]/th[1]//label[1]')
                await el_ckpro[0].click(options={'delay':1000})
                await asyncio.sleep(5)

                #el_elist_btn=await page.xpath('//button[@class="delete-button eds-button eds-button--normal"]')
                el_elist_btn=await page.xpath('//span[text()="Delete"]')

                try:
                    await el_elist_btn[0].click({'delay':1000})
                except Exception as e:
                    logging.info(e)

                await asyncio.sleep(5)

                el_div_pop_btns=await wait_one_xpath(page,'//div[@class="eds-modal"]//div[@class="eds-modal__footer-buttons"]')
                el_qr_btn=await el_div_pop_btns[0].xpath('./button[2]')
                await el_qr_btn[0].click()
                await asyncio.sleep(5)
                aff+=12
                if lastpg:
                    break
            
        await page.close()
        await self.close_browser(browser)
        return {'code':0,'msg':'执行成功','aff':aff}

    async def yb_download_llbb2(self):
        '''下载产品流量报表'''
        browser = await openSunBrowser(self.basic_info,self.task_id)
        #browser=await openChrome()
        if not browser:
            return {'code':-1,'msg':'启动浏览器失败'}

        page = await browser.newPage()
        page.on('dialog', lambda dialog: asyncio.ensure_future(dialog.dismiss()))  # 关闭弹窗

        aff = 0
        url = f'https://{self.host}/datacenter/product/performance'
        await repeat_goto(page, url)
        sss = await self.check_login(page)
        if not sss:
            await self.close_browser(browser)
            return {'code':-2,'msg':'账户登录失败'}
        
        #await asyncio.sleep(3)
        await wait_one_xpath(page,'//span[text()="Export Data"]',max_wait=120)

        excel_content=await download_llbb(page,self.basic_info)
        if not excel_content:
            await page.close()
            await self.close_browser(browser)
            return {'code':-3,'msg':'下载报表超时失败'}
        
        logging.info(f'《{self.dpName}》,{self.bid},开始将流量报表上传至数据库...')   
        aff = dr_LLbb(excel_content,self.basic_info)
        await page.close()
        await self.close_browser(browser)
        return {'code':0,'msg':'执行成功','aff':aff}

    async def yb_cj_list_count(self):
        '''虾皮采集我的产品概况'''


        basic_info=self.basic_info
        bid=self.bid
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{self.host}/portal/product/list/all?operationSortBy=recommend_v2'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        await plw_wait_xpath(page,'//div[@class="list-page-header-title"]')
        self.shopid=await plw_xp_get_shopid(page,basic_info)
        list_info=await plw_xp_get_list_count(page,basic_info)
        listing_limit=await plw_xp_get_product_count_limit(page,basic_info)
        list_info['listing_limit']=listing_limit
        cur_time=datetime.datetime.now() 
        zds=['shopid','bid','BName','GroupName','userName','password','SJBM','YYBM','lg']
        params=[self.shopid,self.bid,self.dpName,self.gname,self.userName,self.password,self.sjbm,self.yybm,basic_info['Country']]
        zds=zds+list(list_info.keys())
        params=params+list(list_info.values())
        rs=self.ms.ExecQuery('select count(*) from ShopeeListCount where shopid=?',(self.shopid,))
        if rs[0][0]==0:
            zds.append('upload_time')
            params.append(cur_time)
            zdstr=','.join(zds)
            wstr=','.join(['?' for _ in params])
            aff=self.ms.ExecNoQuery(f'insert into ShopeeListCount({zdstr}) values ({wstr})',params)
        else:
            zds.append('update_time')
            params.append(cur_time)
            params.append(self.shopid)
            zdstr=','.join([f'{zd}=?' for zd in zds])
            aff=self.ms.ExecNoQuery(f'update ShopeeListCount set {zdstr} where shopid=?',params)

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
       
        return {'code':0,'msg':'采集成功','aff':aff}

    async def yb_cj_wgpro(self):
        '''采集违规产品'''
        self.list_info={'isloaded':False}

        async def intercept_response(res):


            if f"{self.host}/api/v3/mpsku/list/v2/get_list_count" in res.request.url:

                try:
                    json_data=await res.json()
                    count_infos=json_data['data']['count_infos']
                    count_info_dict={count_info['list_type']:count_info['count'] for count_info in count_infos}
                    self.list_info['shopee_deleted']=count_info_dict.get('deleted')
                    self.list_info['isloaded']=True
                except Exception as e:
                    logging.info(f'{self.dpName},{self.bid},解析接口《v3/mpsku/list/v2/get_list_count》数据错误 => {e}')

        violation_type_dict={
            4:'Counterfeit and IP Infringement'
        }

        browser = await openSunBrowser(self.basic_info,self.task_id)
        if not browser:
            return {'code':-1,'msg':'启动浏览器失败'}
        page=await browser.newPage()
        page.on('response', lambda rep: asyncio.ensure_future(intercept_response(rep)))
        purl=f'https://{self.host}/portal/product/list/violation/deleted'
        await repeat_goto(page,purl)
        sss=await self.check_login(page)        
        if not sss:
            await self.close_browser(browser)
            return {'code':-2,'msg':'账户登录失败'}
        wait_count=0
        await asyncio.sleep(3)
        self.shopid=await js_req_shopid(page,self.basic_info)
        while True:
            if self.list_info.get('isloaded') and self.shopid:
                logging.info(f'{self.dpName},{self.bid},成功获取产品概况')
                break
            await asyncio.sleep(1)

            wait_count+=1
            if wait_count>=120:
                logging.info(f'{self.dpName},{self.bid},获取概况数据超时,退出...')
                await page.close()
                await self.close_browser(browser)
                return {'code':-3,'msg':'获取概况数据超时'}
            
        wg_pro_count=self.list_info['shopee_deleted']
        if wg_pro_count==0:
            logging.info(f'{self.dpName},{self.bid},无违规产品')
            await page.close()
            await self.close_browser(browser)
            return {'code':0,'msg':'无违规产品','aff':0}
        
        logging.info(f'{self.dpName},{self.bid},有 {wg_pro_count} 个违规产品,开始获取违规内容...')

        api_url=f'https://{self.host}/api/v3/mpsku/list/v2/get_banned_product_list'
        spdc,ck=await get_ck_and_spc_cds(page)
        wg_pros=[]
        for ppp in range(1,math.ceil(wg_pro_count/48)+1):
            params={'SPC_CDS': spdc,
                    'SPC_CDS_VER': 2,
                    'page_number': ppp,
                    'page_size': 48,
                    'list_type': 'deleted'
            }
            json_data=await make_request(page,api_url,params)
            # with open('wggg.json','w',encoding='utf-8') as f:
            #     json.dump(json_data,f,ensure_ascii=False,indent=4)
            try:
                pros=json_data['data']['products']
            except Exception as e:
                logging.error(f'{self.dpName},{self.bid},json_data获取data错误 => {e}')
            
            for pro in pros:
                pro_dict={}
                try:
                    pro_dict['itemid']=str(pro['id'])
                    pro_dict['PH_itemid']=str(pro['parent_sku'])
                    pro_dict['Product_name']=pro['name']
                    rcode=None 
                    rcode_mat=re.search(r'.*\|(.{8})\|$',pro['name'])
                    if rcode_mat:
                        rcode=rcode_mat.group(1)
                    pro_dict['rcode']=rcode
                    pro_dict['pic']=f"https://down-id.img.susercontent.com/file/{pro['cover_image']}"
                    pro_dict['create_time']=timestamp_to_sql_datetime(pro['create_time'])
                    pro_dict['modify_time']=timestamp_to_sql_datetime(pro['modify_time'])
                    pro_dict['Delete_time']=timestamp_to_sql_datetime(pro['banned_info']['banned_time'])
                    pro_dict['banned_reason']=int(pro['banned_info']['banned_reason'][0])
                    pro_dict['Violation_reason']=pro['banned_info']['reasons'][0]['description']
                    pro_dict['Suggestion']=pro['banned_info']['reasons'][0]['explanation']
                    wg_status=pro['status']
                    if violation_type_dict.get(wg_status):
                        pro_dict['Violation_type']=violation_type_dict.get(wg_status)
                    else:
                        pro_dict['Violation_type']=str(wg_status)
                    wg_pros.append(pro_dict)

                except Exception as e:
                    logging.error(f'{self.dpName},{self.bid},解析违规参数错误 => {e}')

        if not wg_pros:
            await page.close()
            await self.close_browser(browser)
            return {'code':-3,'msg':'获取违规产品失败'}
        logging.info(f'{self.dpName},{self.bid},成功获取 {len(wg_pros)} 个违规产品,开始更新到数据表《ShopeeDeletePro》')
        cur_time=datetime.datetime.now() 

        aff=0
        end_qq=0
        for wg_pro in wg_pros:
            zds=['shopid','bid','BName','GroupName','userName','password','SJBM','YYBM','lg']
            params=[self.shopid,self.bid,self.dpName,self.gname,self.userName,self.password,self.sjbm,self.yybm,'YinNi']
            cur_itemid=wg_pro['itemid']
            ph_itemid=wg_pro['PH_itemid']
            if ph_itemid:
                end_qq+=self.ms.ExecNoQuery('update proshopeeph set daochu=-6 where itemid=?',(ph_itemid,))
            zds=zds+list(wg_pro.keys())
            params=params+list(wg_pro.values())
            rs=self.ms.ExecQuery('select count(*) from ShopeeDeletePro where shopid=? and itemid=?',(self.shopid,cur_itemid))
            if rs[0][0]==0:
                zds.extend(['upload_time','update_time'])
                params.extend([cur_time,cur_time])
                zdstr=','.join(zds)
                wstr=','.join(['?' for _ in params])
                
                aff+=self.ms.ExecNoQuery(f'insert into ShopeeDeletePro({zdstr}) values ({wstr})',params)
            else:
                zds.append('update_time')
                params.append(cur_time)
                params.extend([self.shopid,cur_itemid])
                zdstr=','.join([f'{zd}=?' for zd in zds])
                aff+=self.ms.ExecNoQuery(f'update ShopeeDeletePro set {zdstr} where shopid=? and itemid=?',params)

        await page.close()
        await self.close_browser(browser)
        return {'code':0,'msg':f'采集成功,拉黑原始数据:{end_qq}','aff':aff}

    async def yb_cj_add_cost(self):
        '''加购成本表补充广告费'''
        browser = await openSunBrowser(self.basic_info,self.task_id)
        #browser=await openChrome()
        if not browser:
            return {'code':-1,'msg':'启动浏览器失败'}
        page=await browser.newPage()
        st_time,ed_time=calculate_timestamps2(30)

        url=f'https://{self.host}/portal/marketing/pas/index?from={st_time}&to={ed_time}&type=new_cpc_homepage&group=last_month'
        await repeat_goto(page,url)
        sss=await self.check_login(page)
        if not sss:
            await self.close_browser(browser)
            return {'code':-2,'msg':'账户登录失败'}
        
        await wait_one_xpath(page,'//div[@class="export-button"]',max_wait=180)
        shopid=await js_req_shopid(page,self.basic_info)
        self.basic_info['shopid']=shopid
        campaign_infos=await get_all_camp_info(page,self.basic_info,dayjg=30)
        probb=await get_xp_probb(page,self.basic_info)
        probb_cart_dict={}

        for pro in probb:
            ccc_itemid=str(str(pro['id']))
            probb_cart_dict[ccc_itemid]={
                'add_to_cart_buyers':pro['add_to_cart_buyers'],
                'conversions':pro['confirmed_buyers'],
                'conversion_rate':pro['uv_to_add_to_cart_rate'],
                'cart_to_conversion_rate':round(pro['confirmed_buyers']/pro['add_to_cart_buyers'],4)
            }
        
        suc=0
        cur_timetstamp=int(time.time())
        pj=1

        for entry in campaign_infos:

            camid=str(entry['campaign']['campaign_id'])
            itemid=str(entry['manual_product_ads']['item_id'])
            all_cost=entry['report']['cost']/100000
            camp_broad_order=entry['report']['broad_order']
            start_timetstamp=entry['campaign']['start_time']
            pname=entry['title']
            create_days=int((cur_timetstamp-start_timetstamp)/86400)
            ad_url=f'https://{self.host}/portal/marketing/pas/product/manual/{camid}?group=last_month'
            purl=f"https://{self.host.replace('seller.','')}/product/{shopid}/{itemid}/"
            res_Xpcamp=await update_XPcamp(page,self.basic_info,entry)
            logging.info(f'店铺:《{self.dpName}》,{self.bid},第{pj}个pid:{itemid},更新《campaign》,状态:{res_Xpcamp}')
            try:
                
                pro_info=probb_cart_dict.get(itemid)
                avg_cost=None
                cost_per_conversion=None


                if pro_info is not None:
                    add_cart_count=pro_info['add_to_cart_buyers']
                    conversions=pro_info['conversions']
                    conversion_rate=pro_info['conversion_rate']
                    cart_to_conversion_rate=pro_info['cart_to_conversion_rate']
                    if conversions>0:
                        cost_per_conversion=round(all_cost/conversions,2)
                    avg_cost=round(all_cost/add_cart_count,2)
                    all_cost=round(all_cost,2)

                    zds=['product_id','campaign_id','purl','ad_url','shopid','cost_30day','add_cart_30day','avg_cost',
                        'bid','BName','GroupName','userName','password','SJBM','YYBM','create_days','Product_Name_Ad_Name',
                        'conversions','camp_broad_order','conversion_rate','cart_to_conversion_rate','cost_per_conversion'
                        ]
                    params=[itemid,camid,purl,ad_url,shopid,all_cost,add_cart_count,avg_cost,
                            self.bid,self.dpName,self.gname,self.userName,self.password,self.sjbm,self.yybm,create_days,pname,
                            conversions,camp_broad_order,conversion_rate,cart_to_conversion_rate,cost_per_conversion
                            ]
                    zds_on=['product_id']
                    aff=self.ms.merge_into('ShopeeADCost',zds,params,zds_on,True)
                    
                    logging.info(f'店铺:《{self.dpName}》,{self.bid},第{pj}个pid:{itemid},获取30天广告总消费:{all_cost},获取30天加购总人数:{add_cart_count}')
                else:
                    zds=['product_id','campaign_id','purl','ad_url','shopid','cost_30day','add_cart_30day',
                        'bid','BName','GroupName','userName','password','SJBM','YYBM','create_days','Product_Name_Ad_Name',
                        'conversions','camp_broad_order','conversion_rate','cart_to_conversion_rate','cost_per_conversion'
                        ]
                    params=[itemid,camid,purl,ad_url,shopid,all_cost,0,
                            self.bid,self.dpName,self.gname,self.userName,self.password,self.sjbm,self.yybm,create_days,pname,
                            0,camp_broad_order,None,None,cost_per_conversion
                            ]
                    zds_on=['product_id']
                    aff=self.ms.merge_into('ShopeeADCost',zds,params,zds_on,True)
                    logging.info(f'店铺:《{self.dpName}》,{self.bid},第{pj}个pid:{itemid},获取30天广告总消费:{all_cost},获取30天加购总人数失败')

                suc+=aff 
                logging.info(f'店铺:《{self.dpName}》,{self.bid},第{pj}个pid:{itemid},30天平均广告成本:{avg_cost},更新状态:{aff}')
                
            except Exception as e:
                traceback.print_exc()
                logging.info(f'店铺:《{self.dpName}》,{self.bid},第{pj}个pid,出错 => {e}')
            pj+=1

        await page.close()
        await self.close_browser(browser)
        return {'code':0,'msg':f'采集加购成本成功','aff':suc}

    async def yb_pause_ad(self):
        '''测品广告管理'''
        browser = await openSunBrowser(self.basic_info,self.task_id)
        #browser=await openChrome()
        if not browser:
            return {'code':-1,'msg':'启动浏览器失败'}
        page=await browser.newPage()
        st_time,ed_time=calculate_timestamps2(90)
        url=f'https://{self.host}/portal/marketing/pas/index?from={st_time}&to={ed_time}&type=new_cpc_homepage&group=last_month'
        await repeat_goto(page,url)
        sss=await self.check_login(page)
        if not sss:
            await self.close_browser(browser)
            return {'code':-2,'msg':'账户登录失败'}
        
        sql_str=f'''select product_id,campaign_id from ShopeeADCost 
                where bid='{self.bid}'
                and create_days>3
                and (
                (cost_30day>=10000 and add_cart_30day=0) 
                or 
                (cost_30day>=10000 and avg_cost>=4000 and conversions=0)
                or
                (conversion_rate<0.06 and cost_30day>=10000 and conversions=0)
                )
            '''
        rs_shadcost=self.ms.ExecQuery(sql_str)
        ccc_pids=[r[0] for r in rs_shadcost]
        
        await wait_one_xpath(page,'//div[@class="export-button"]',max_wait=180)
        all_need_pause,all_camp_ids=await get_need_pause_ad(page,self.basic_info,ccc_pids)
        
        logging.info(f'店铺:《{self.dpName}》,{self.bid},共{len(all_camp_ids)} 广告,需暂停 {len(all_need_pause)} 个')
        if not all_need_pause:
            await page.close()
            await self.close_browser(browser)
            return {'code':0,'msg':'无需暂停任何广告','aff':0}
        
        res=await pause_ad(page,self.basic_info,[int(campid) for campid in all_need_pause]) 
        code=res['code']
        if code==0:
            logging.info(f'店铺:《{self.dpName}》,{self.bid},成功暂停 {len(all_need_pause)} 个广告')
        else:
            logging.info(f'店铺:《{self.dpName}》,{self.bid},暂停失败')
        await page.close()
        await self.close_browser(browser)
        return res

    async def yb_get_order(self):
        '''虾皮采集后台订单'''

        basic_info=self.basic_info
        bid=self.bid
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{self.host}/portal/sale/order'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        await plw_wait_xpath(page,'//div[@class="text-section"]')
        msg=''
        aff=0
        aff_odder=await plw_update_XPOrder(page,self.basic_info)
        
        if aff_odder is not None:
            tms.ExecNoQuery('update houtai set order_updated=1 where BrowserID=?',(self.bid,))
            aff+=1
        msg+='更新订单信息成功,' if aff_odder is not None else '更新订单信息失败,'


        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return {'code':0,'msg':msg,'aff':aff}

    async def yb_get_stock(self):
        '''虾皮采集后台库存'''

        basic_info=self.basic_info
        bid=self.bid
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{self.host}/portal/product/list/all?operationSortBy=recommend_v2'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        await plw_wait_xpath(page,'//div[@class="list-page-header-title"]')
        msg=''
        aff=0
        aff_stock=await plw_update_XPStock(page,self.basic_info)
        if aff_stock is not None:
            aff+=1
        msg+='更新产品库存成功,' if aff_stock is not None else '更新产品库存失败,'

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return {'code':0,'msg':msg,'aff':aff}

    async def yb_dc_ad_phpro(self):
        '''导出广告产品'''
        self.task_id=7
        browser=await openSunBrowser(self.basic_info,self.task_id)
        #browser= await openChrome()
        if not browser:
            return {'code':-1,'msg':'启动浏览器失败'}
        page=await browser.newPage()

        await repeat_goto(page,f'https://{self.host}/portal/marketing/pas/index')
        sss=await self.check_login(page)
        if not sss:
            await self.close_browser(browser)
            return {'code':-2,'msg':'账户登录失败'}
        
        await wait_one_xpath(page,'//div[@class="export-button"]')
     
        camp_dict=await get_camps_with_tit(page,self.basic_info)
        need_dc_phitemids=[]
        not_find_ynitemids=[]
        need_pause_campid=[]
        for itemid,vvv in camp_dict.items():
            campid,ptitle=vvv
            mat_rcode= re.search(r'.*\|(.{8})\|$',ptitle)
            if mat_rcode:
                rcode=mat_rcode.group(1)
                rs_ph=tms.ExecQuery('select itemid from randomcodes where randomcode=?',(rcode,))
                need_dc_phitemids.append(rs_ph[0][0])
                need_pause_campid.append(int(campid))
            else:
                rs_ph=tms.ExecQuery('select top 1 itemid,yntitleRcode from proshopeeph where yntitle=?',(ptitle,))
                if len(rs_ph)>0:
                    ph_itemid,yntitleRcode=rs_ph[0]
                    print(f'itemid:{itemid},标题匹配到大数据表{ph_itemid}')
                    need_dc_phitemids.append(ph_itemid)
                    need_pause_campid.append(int(campid))
                else:
                    not_find_ynitemids.append([itemid,campid])
        
        logging.info(f'店铺:《{self.dpName}》,{self.bid},可导出:{len(need_dc_phitemids)}个,不可导出:{len(not_find_ynitemids)}个')
        logging.info(f'店铺:《{self.dpName}》,{self.bid},开始导出 {len(need_dc_phitemids)} 个产品...')

        aff=dc_ty_pro(need_dc_phitemids)
        res_pau=await pause_ad(page,self.basic_info,need_pause_campid)
        print(res_pau)
        await page.close()
        await self.close_browser(browser)
        return {'code':0,'msg':'采集成功','aff':aff}

    async def download_basic_temp(self):
        
        browser=await openSunBrowser(self.basic_info,11)
        #browser= await openChrome()
        if not browser:
            return {'code':-1,'msg':'启动浏览器失败'}
        page=await browser.newPage()

        await repeat_goto(page,f'https://{self.host}/portal/product-mass/import/download')
        sss=await self.check_login(page)
        if not sss:
            await self.close_browser(browser)
            return {'code':-2,'msg':'账户登录失败'}
        await asyncio.sleep(5)
        
        res_path=await js_downlond_basic_mb(page,self.basic_info)
        if res_path:
            res={'code':0,'msg':'下载成功','path':res_path}
        else:
            res={'code':1,'msg':'下载失败'}
        await page.close()
        await self.close_browser(browser)
        return res

    async def yb_update_campaign(self):
        '''广告产品参数更新'''
        browser = await openSunBrowser(self.basic_info,self.task_id)
        #browser=await openChrome()
        if not browser:
            return {'code':-1,'msg':'启动浏览器失败'}
        page=await browser.newPage()
        st_time,ed_time=get_shopee_timestamp()
        url=f'https://{self.host}/portal/marketing/pas/index?from={st_time}&to={ed_time}&type=new_cpc_homepage&group=last_month'
        await repeat_goto(page,url)
        sss=await self.check_login(page)
        if not sss:
            await self.close_browser(browser)
            return {'code':-2,'msg':'账户登录失败'}
        
        await asyncio.sleep(10)
        res=await update_campaign(page,self.basic_info)

        if res is None:
            await page.close()
            await self.close_browser(browser)
            return {'code':-3,'msg':'获取广告数据失败'}
        
        await page.close()
        await self.close_browser(browser)
        return {'code':0,'msg':'采集成功','aff':res}

    async def edit_add_kol(self,page:Page,cmmid):

        basic_info=self.basic_info
        host=self.host
        dpName=self.dpName
        bid=self.bid

        await plw_wait_xpath(page,'//span[text()="Add Products"]')
        await asyncio.sleep(3)
        logging.info(f'店铺:《{dpName}》,{bid},达人编辑页面刷新完毕')
        purl=f'https://{host}/portal/web-seller-affiliate/target_campaign/edit/{cmmid}?is_from_edit=1'

        aff=0
        zd_kk_num=None
        while True:
            await plw_repeat_goto(page,purl)
            sss=await plw_check_login(page,basic_info)
            if not sss:
                return 
            await plw_wait_xpath(page,'//span[text()="Add Products"]')
            await asyncio.sleep(3)
            logging.info(f'店铺:《{dpName}》,{bid},达人页面刷新完毕')
            cmm_dict=await plw_get_cmm_list(page,basic_info)

            cur_kol_num=cmm_dict[cmmid]

            if cur_kol_num>=200:
                logging.info(f'店铺:《{dpName}》,{bid},计划:{cmmid},当前达人数:{cur_kol_num},达标退出')
                break
            else:
                logging.info(f'店铺:《{dpName}》,{bid},计划:{cmmid},当前达人数:{cur_kol_num},需补充达人{200-cur_kol_num}')

            

            el_kol_div=page.locator('xpath=//div[@id="createTargetCampaign_affiliateIdList"]')
            el_kol_trs=el_kol_div.locator('xpath=.//tr[@data-row-key]')
            kkk_num=8
            if zd_kk_num:
                kkk_num=zd_kk_num
            if 200-cur_kol_num<kkk_num:
                kkk_num=200-cur_kol_num
            kol_list=get_kol(self.basic_info,kkk_num)
            kol_ids=[kitem[1] for kitem in kol_list]
            kol_id_username_map={kitem[1]:kitem[2] for kitem in kol_list}
            try:
                while True:
                    count = await el_kol_trs.count()

                    data_row_keys = []                
                    for ej in range(count):
                        ctr = el_kol_trs.nth(ej)
                        key = await ctr.get_attribute('data-row-key')
                        if key in kol_ids:
                            data_row_keys.append(key)

                    
                    need_add_kol_ids=set(kol_ids)-set(data_row_keys)

            
                    if len(need_add_kol_ids)==0:
                        logging.info(f'店铺:《{dpName}》,{bid},已成功添加全部 {len(data_row_keys)} 个达人')
                        break
        
                    logging.info(f'店铺:《{dpName}》,{bid},还需添加:{len(need_add_kol_ids)}个达人')
                    for kj,kid in enumerate(need_add_kol_ids,start=1):
                        kol_username=kol_id_username_map[kid]
                        logging.info(f'店铺:《{dpName}》,{bid},开始添加第{kj}个达人:《{kol_username}》')
                        try:
                            async with page.expect_response(lambda res: "/api/v3/affiliateplatform/creator/list" in res.url,timeout=60000) as response_info:
                                el_add_kol=page.locator('xpath=//span[text()="Add Affiliates"]')
                                await el_add_kol.click(delay=200)
                        except Exception as e:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {kj}个达人搜索出错 => {e}')
                            el_close=page.locator('//span[@aria-label="close"]')
                            await el_close.click(delay=200) 
                            continue
                        
                        el_ipt_uname=page.locator('xpath=//input[@id="username"]')
                        await el_ipt_uname.fill(kol_username)
                        await asyncio.sleep(1)
                        await el_ipt_uname.press('Enter',delay=100)
                        try:
                            await page.wait_for_selector(f'xpath=//tr[@data-row-key="{kid}"]')
                            el_tr_ckol= page.locator(f'xpath=//tr[@data-row-key="{kid}"]')
                        except Exception as e:
                            el_close=page.locator('//span[@aria-label="close"]')
                            kol_ids.remove(kid)
                            await el_close.click(delay=200)
                            aff_del=self.ms.ExecNoQuery(f'delete from ShopeeKOL where affiliate_id=?',(kid,))
                            logging.info(f'店铺:《{dpName}》,{bid},第 {kj}个等待搜索结果超时 => {e},删除达人:《{kol_username}》 => {aff_del}')
                            continue
                        await asyncio.sleep(1)
                        el_ckolck=el_tr_ckol.locator('xpath=./td[1]/label[1]')
                        await el_ckolck.click(delay=200)
                        await asyncio.sleep(2)

                        el_qr_btn=page.locator('xpath=//div[@class="eds-react-modal__body"]//span[text()="Confirm"]')
                        await el_qr_btn.click(delay=200)
                        await asyncio.sleep(2)


                async with page.expect_response(lambda res: "/api/v3/affiliateplatform/gql?q=UpdateNewTargetCampaignMutation" in res.url,timeout=60000) as resp_upd:
                    el_Submit=page.locator('xpath=//span[text()="Submit"]')
                    await el_Submit.click(delay=200)
                
                try:
                    res_00=await resp_upd.value
                    json_data=await res_00.json()
                    code000=None
                    if json_data.get('data'):
                        if json_data['data'].get('UpdateNewTargetCampaign'):
                            code000=json_data['data']['UpdateNewTargetCampaign'].get('code')
                    
                    
                    if code000==0:
                        kidstr=','.join([str(kk[0]) for kk in kol_list])
                        aff_dr=self.ms.ExecNoQuery(f'update ShopeeKOL set is_yao_qing=1 where id in ({kidstr})')
                        logging.info(f'店铺:《{dpName}》,{bid},标记 {aff_dr} 个达人ID,设置已邀请')
                        aff+=aff_dr
                    
                    else:
                        kidstr=','.join([str(kk[0]) for kk in kol_list])
                        aff_set=self.ms.ExecNoQuery(f'update ShopeeKOL set yao_qing_bid=null where id in ({kidstr})')
                        now_date_time=datetime.datetime.now()
                        aff_dp=self.ms.ExecNoQuery('update houtai set kol_wait_time=? where BrowserID=?',(now_date_time,self.bid))
                        logging.info(f'店铺:《{dpName}》,{bid},提交失败,重置 {aff_set} 个达人ID,标记店铺禁用时间:{now_date_time} =>{aff_dp}')
                        return
                except Exception as e:
                    
                    traceback.print_exc()
                    kidstr=','.join([str(kk[0]) for kk in kol_list])
                    aff_set=self.ms.ExecNoQuery(f'update ShopeeKOL set yao_qing_bid=null where id in ({kidstr})')
                    logging.info(f'店铺:《{dpName}》,{bid},提交跳转验证码,重置 {aff_set} 个达人ID,等待120秒')
                    await asyncio.sleep(120)
                    zd_kk_num=kkk_num-1 if not zd_kk_num else zd_kk_num-1
                    if zd_kk_num<5:
                        zd_kk_num=5
                    continue
                        

                await asyncio.sleep(3)
            except Exception as e:
                traceback.print_exc()
                kidstr=','.join([str(kk[0]) for kk in kol_list])
                aff_set=self.ms.ExecNoQuery(f'update ShopeeKOL set yao_qing_bid=null where id in ({kidstr})')
                logging.info(f'店铺:《{dpName}》,{bid},提交出错,重置 {aff_set} 个达人ID')
                return
        return aff

    async def yb_add_affiliate2(self):

        '''自动邀请达人'''
        basic_info=self.basic_info
        host=self.host
        dpName=self.dpName
        bid=self.bid
        jjtime=self.basic_info['kol_wait_time']
        now=datetime.datetime.now()
        if jjtime:
            if now - jjtime < datetime.timedelta(hours=4):
                logging.info(f"店铺:《{dpName}》,{bid},禁用4小时中")
                return {'code':0,'msg':'禁用中','aff':0}

        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()
        #page=defaultContext.pages[0]
        t0=asyncio.create_task(plw_bring_to_front_if_needed(page))


        url=f'https://{host}/portal/web-seller-affiliate/target_campaign/create?pre_page=ams_target_campaign&pre_target=create_new_campaign'
        

        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        kol_list=[]
        kol_num=1
        try:
            await plw_wait_xpath(page,'//span[text()="Add Products"]')
            await asyncio.sleep(3)
            logging.info(f'店铺:《{dpName}》,{bid},达人页面刷新完毕')
            

            cmm_dict=await plw_get_cmm_list(page,basic_info)

            if len(cmm_dict.keys())>=100:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':0,'msg':'当前已经达到100个达人计划','aff':0}
            
            target_cmmid=None
            for cmmid,knum in cmm_dict.items():
                if knum<190:
                    target_cmmid=cmmid
                    break
            
            if target_cmmid is None:
                logging.info(f'店铺:《{dpName}》,{bid},当前没有需补充达人的计划,新建达人计划')
                await asyncio.sleep(3)
                await page.close()
                await asyncio.sleep(3)
                page=await defaultContext.new_page()
                await plw_repeat_goto(page,url)
                sss=await plw_check_login(page,basic_info)
                if not sss:
                    await page.close()
                    await plw.stop()
                    close_SunBrowser(bid,self.task_id)
                    return {'code':-2,'msg':'账户登录失败'} 

                #第一步选择所有可选产品
                logging.info(f'店铺:《{dpName}》,{bid},第一步,选择所有可选产品')
                while True:
                    el_btn_add_pro=await plw_wait_xpath(page,'//span[text()="Add Products"]')
                    await el_btn_add_pro.click(delay=200)
                    el_select_pro=await plw_wait_xpath(page,'//div[@class="eds-react-modal__title"]')
                    if el_select_pro:
                        logging.info(f'店铺:《{dpName}》,{bid},已打开产品弹窗')
                        break
                    await asyncio.sleep(1)
            
                await asyncio.sleep(10)

                # 循环滚动到底部

                logging.info(f'店铺:《{dpName}》,{bid},开始滚动到产品列表底部')

                for _ in range(20):
                    await page.evaluate('''
                        () => {
                            const el = document.querySelector('div.eds-react-table-body');
                            if (el) el.scrollTop += 1500;
                        }
                    ''')
                    await asyncio.sleep(1)  # 等待新数据加载
                
                logging.info(f'店铺:《{dpName}》,{bid},点击全选产品按钮')
                while True:

                    el_ck_all=await plw_wait_xpath(page,'//th/div[1]/label[@class="eds-react-checkbox"]')
                    if el_ck_all:
                        await el_ck_all.click(delay=200)
                        await asyncio.sleep(3)
                    el_select_num=await plw_wait_xpath(page,'//span/strong[1]')
                    select_num= await el_select_num.text_content()
                    select_num=select_num.strip()
                    if select_num and select_num!='0':
                        logging.info(f'店铺:《{dpName}》,{bid},当前已全选产品:{select_num}个')
                        break
                    await asyncio.sleep(3)

                logging.info(f'店铺:《{dpName}》,{bid},点击confirm产品')
                while True:
                    btn_qr=await plw_wait_xpath(page,'//span[text()="Confirm"]')
                    if btn_qr:
                        await btn_qr.click(delay=200)
                        await asyncio.sleep(3)
                    el_th_tit=await plw_wait_xpath(page,'//th[text()="Commission Rate"]')
                    if el_th_tit:
                        break
                    await asyncio.sleep(3)
                
                logging.info(f'店铺:《{dpName}》,{bid},修改达人抽成比例')

                el_ptrs= page.locator('xpath=//tr[@data-row-key]')
                for ej in range((await el_ptrs.count())):
                    el_ptr=el_ptrs.nth(ej)
                    el_rate_ipt=el_ptr.locator('xpath=./td[3]//input')
                    ipt_value=await el_rate_ipt.input_value()
                    if ipt_value=='10':
                        logging.info(f'店铺:《{dpName}》,{bid},第{ej+1}个产品抽成已经是10%跳过')
                        continue
                    await el_rate_ipt.fill('10')
                    logging.info(f'店铺:《{dpName}》,{bid},第{ej+1}个产品更改比例为10%')
                    await asyncio.sleep(3)
                    el_error=el_ptr.locator('xpath=./td[3]//div[@class="eds-react-form-item__error"]')
                    if (await el_error.count())>0:
                        el_err_txt=await el_error.text_content()
                        if 'Please set higher rate than' in el_err_txt:
                            logging.info(f'店铺:《{dpName}》,{bid},第{ej+1}个是广告产品需为11%')
                            await el_rate_ipt.fill('11')
                    await asyncio.sleep(1)
                


                logging.info(f'店铺:《{dpName}》,{bid},开始邀请 {kol_num} 个达人')

                el_kol_div=page.locator('xpath=//div[@id="createTargetCampaign_affiliateIdList"]')
                el_kol_trs=el_kol_div.locator('xpath=.//tr[@data-row-key]')
                while True:
                    try:
                        if (await el_kol_trs.count())>0:
                            logging.info(f'店铺:《{dpName}》,{bid},先删除系统推荐达人')
                            el_kol_ck_all=el_kol_div.locator('xpath=.//th[text()="Affiliates"]/..//label[@class="eds-react-checkbox"]')
                            await el_kol_ck_all.click(delay=200)
                            await asyncio.sleep(2)
                            el_del_kol=page.locator('xpath=//span[text()="Batch Delete"]')
                            await el_del_kol.click(delay=200)
                            await asyncio.sleep(2)
                        else:
                            logging.info(f'店铺:《{dpName}》,{bid},成功删除所有系统推荐达人')
                            break
                    except Exception as e:
                        traceback.print_exc()
                        print(e)
                
                if dpName not in ('1号大店','2号大店'):
                    kol_list=get_kol(self.basic_info,1)
                else:
                    kol_list=get_kol(self.basic_info,200)
                kol_ids=[kitem[1] for kitem in kol_list]
                kol_id_username_map={kitem[1]:kitem[2] for kitem in kol_list}

                while True:
                    count = await el_kol_trs.count()

                    data_row_keys = []
                    del_count=0
                    
                    for ej in range(count):
                        ctr = el_kol_trs.nth(ej)
                        key = await ctr.get_attribute('data-row-key')
                        if key in kol_ids:
                            data_row_keys.append(key)
                        else:
                            ctd=ctr.locator('xpath=./td[1]/label[1]')
                            await ctd.click(delay=200)
                            del_count+=1
                            await asyncio.sleep(1)
                    
                    if del_count>0:
                        el_btn_del_kol=page.locator('xpath=//span[text()="Batch Delete"]/..')
                        class_txt= await el_btn_del_kol.get_attribute('class')
                        if 'disabled' not in class_txt:
                            await el_btn_del_kol.click(delay=200)
                            await asyncio.sleep(2)
                            logging.info(f'店铺:《{dpName}》,{bid},删除 {del_count} 个非数据库达人')

                    need_add_kol_ids=set(kol_ids)-set(data_row_keys)
                    need_del_kol_ids=set(data_row_keys)-set(kol_ids)

                    if len(need_add_kol_ids)==0 and len(need_del_kol_ids)==0:
                        logging.info(f'店铺:《{dpName}》,{bid},已成功添加全部 {len(data_row_keys)} 个达人')
                        break
          
                    logging.info(f'店铺:《{dpName}》,{bid},还需添加:{len(need_add_kol_ids)}个达人')
                    for kj,kid in enumerate(need_add_kol_ids,start=1):
                        kol_username=kol_id_username_map[kid]
                        logging.info(f'店铺:《{dpName}》,{bid},开始添加第{kj}个达人:《{kol_username}》')
                        try:
                            async with page.expect_response(lambda res: "/api/v3/affiliateplatform/creator/list" in res.url,timeout=60000) as response_info:
                                el_add_kol=page.locator('xpath=//span[text()="Add Affiliates"]')
                                await el_add_kol.click(delay=200)
                        except Exception as e:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {kj}个达人搜索出错 => {e}')
                            el_close=page.locator('//span[@aria-label="close"]')
                            await el_close.click(delay=200) 
                            continue
                        
                        el_ipt_uname=page.locator('xpath=//input[@id="username"]')
                        await el_ipt_uname.fill(kol_username)
                        await asyncio.sleep(1)
                        await el_ipt_uname.press('Enter',delay=100)
                        try:
                            await page.wait_for_selector(f'xpath=//tr[@data-row-key="{kid}"]')
                            el_tr_ckol= page.locator(f'xpath=//tr[@data-row-key="{kid}"]')
                        except Exception as e:
                            el_close=page.locator('//span[@aria-label="close"]')
                            kol_ids.remove(kid)
                            await el_close.click(delay=200)
                            aff_del=self.ms.ExecNoQuery(f'delete from ShopeeKOL where affiliate_id=?',(kid,))
                            logging.info(f'店铺:《{dpName}》,{bid},第 {kj}个等待搜索结果超时 => {e},删除达人:《{kol_username}》 => {aff_del}')

                            continue
                        await asyncio.sleep(1)
                        el_ckolck=el_tr_ckol.locator('xpath=./td[1]/label[1]')
                        await el_ckolck.click(delay=200)
                        await asyncio.sleep(2)

                        el_qr_btn=page.locator('xpath=//div[@class="eds-react-modal__body"]//span[text()="Confirm"]')
                        await el_qr_btn.click(delay=200)
                        await asyncio.sleep(2)

                
                await asyncio.sleep(3)

                logging.info(f'店铺:《{dpName}》,{bid}第三步,填写Campaign')
                el_camp_name=page.locator('xpath=//input[@id="createTargetCampaign_commissionName"]')
                await el_camp_name.fill(f'Harga tinggi! Tingkat konversi tinggi! Komisi tinggi!({getTimeStr()})')
                await asyncio.sleep(3)

                new_dt = datetime.datetime.now().replace(minute=0, second=0, microsecond=0) + datetime.timedelta(hours=1)

                mmm=new_dt.month
                ddd=new_dt.day
                hhh=new_dt.hour

                logging.info(f'店铺:《{dpName}》,{bid},设置计划开始时间:{mmm}月{ddd}日,{hhh}:00')
                while True:
                    try:
                        
                        el_icon=page.locator('xpath=//div[@class="icon-box"]')
                        await el_icon.click()
                        await asyncio.sleep(3)
                        await page.wait_for_selector('xpath=//div[@class="eds-react-date-picker__input eds-react-date-picker__input--normal eds-react-popover-open"]')
                        break
                    except Exception as e:
                        traceback.print_exc()
                        print(e)
                    await asyncio.sleep(1)
                
                #选择日期
                el_panel=page.locator('xpath=//div[@class="eds-react-date-picker__panel"]')
                el_panel_day=el_panel.locator('xpath=./div[2]/div[@class="eds-react-date-picker__table-row"]/div/div[1]')

                for dj in range(await el_panel_day.count()):
                    el_ddd=el_panel_day.nth(dj)
                    cur_css=await el_ddd.get_attribute('class')
                    if 'disabled' in cur_css:
                        continue
                    if str(ddd)==(await el_ddd.text_content()):
                        await el_ddd.click(delay=200)
                        logging.info(f'店铺:《{dpName}》,{bid},成功选择 {ddd} 号')
                        break
                
                el_time_div=page.locator('xpath=//div[@class="eds-react-time-picker"]')

                el_hour_lis=el_time_div.locator('xpath=./div[1]/div[2]//li/div[1]')
                for hj in range(await el_hour_lis.count()):
                    el_hhh=el_hour_lis.nth(hj)
                    if f'{hhh:02d}' == (await el_hhh.text_content()).strip():
                        await el_hhh.click(delay=200)
                        logging.info(f'店铺:《{dpName}》,{bid},成功选择 {hhh} 点')
                        break
                await asyncio.sleep(3)
                el_fff_lis=el_time_div.locator('xpath=./div[1]/div[3]//li/div[1]')
                for fj in range(await el_fff_lis.count()):
                    el_fff=el_fff_lis.nth(fj)
                    if f'00' == (await el_fff.text_content()).strip():
                        await el_fff.click(delay=200)
                        logging.info(f'店铺:《{dpName}》,{bid},成功选择 {00} 分')
                        break
                
                await asyncio.sleep(3)
                el_date_config=page.locator('xpath=//div[@class="eds-react-date-picker"]//span[text()="Confirm"]')
                await el_date_config.click(delay=200)
                await asyncio.sleep(3)

                el_meg_to_kol=page.locator('//textarea[@id="createTargetCampaign_sellerMessage"]')
                await el_meg_to_kol.fill('Harga Premium! Tingkat Konversi Tinggi! Komisi Besar!Kami tunggu kerjasamanya!')
                await asyncio.sleep(3)

                logging.info(f'店铺:《{dpName}》,{bid}第四步,提交计划')

    
    
                async with page.expect_response(lambda res: "/api/v3/affiliateplatform/gql?q=CreateTargetCampaignEnhancementMutation" in res.url,timeout=60000) as resp_cre:
                    el_Submit=page.locator('xpath=//span[text()="Submit"]')
                    await el_Submit.click(delay=200)
                await asyncio.sleep(3)
                
                try:
                    res00 =await resp_cre.value
                    json_data=await res00.json()
                    cmssid=None
                    if json_data.get('data'):
                        if json_data['data'].get('CreateTargetCampaignEnhancement'):
                            cmssid=json_data['data']['CreateTargetCampaignEnhancement'].get('commissionId')
                

                    if cmssid:
                        
                        kidstr=','.join([str(kk[0]) for kk in kol_list])
                        aff_dr=self.ms.ExecNoQuery(f'update ShopeeKOL set is_yao_qing=1 where id in ({kidstr})')
                        logging.info(f'店铺:《{dpName}》,{bid},发布达人计划成功,标记 {aff_dr} 个达人ID已邀请,计划ID:{cmssid}')
                        await asyncio.sleep(3)
                        aff_bc=await self.edit_add_kol(page,cmssid)
                        res={'code':0,'msg':'执行成功','aff':aff_bc}

                    
                    else:
                        res={'code':-4,'msg':'执行失败'}
                        kidstr=','.join([str(kk[0]) for kk in kol_list])
                        aff_set=self.ms.ExecNoQuery(f'update ShopeeKOL set yao_qing_bid=null where id in ({kidstr})')
                        logging.info(f'店铺:《{dpName}》,{bid},提交计划失败,重置 {aff_set} 个达人ID')
                except Exception as e:
                    res={'code':-5,'msg':'跳转验证码','aff':0}
                    if kol_list:
                        kidstr=','.join([str(kk[0]) for kk in kol_list])
                        aff_set=self.ms.ExecNoQuery(f'update ShopeeKOL set yao_qing_bid=null where id in ({kidstr})')
                        logging.info(f'店铺:《{dpName}》,{bid},跳转验证码,重置 {aff_set} 个达人ID')
                    await asyncio.sleep(600)
                    
            else:
                logging.info(f'店铺:《{dpName}》,{bid},将达人计划:{target_cmmid},补充至200')
                aff_bc=await self.edit_add_kol(page,target_cmmid)
                res={'code':-4,'msg':'执行失败','aff':aff_bc} 

            btn_qr3=page.locator('xpath=//div[@class="eds-react-modal__box"]//span[text()="Confirm"]')
            if (await btn_qr3.count())==1:
                await btn_qr3.click(delay=200)
            await asyncio.sleep(3)

            
        except Exception as e:
            traceback.print_exc()
            if kol_list:
                kidstr=','.join([str(kk[0]) for kk in kol_list])
                aff_set=self.ms.ExecNoQuery(f'update ShopeeKOL set yao_qing_bid=null where id in ({kidstr})')
                logging.info(f'店铺:《{dpName}》,{bid},重置 {aff_set} 个达人ID')
            logging.info(f'店铺:《{dpName}》,{bid},出错 => {e}')
            res={'code':-3,'msg':str(e)}

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return res

    async def yb_stop_affiliate(self):
        basic_info=self.basic_info
        host=self.host
        dpName=self.dpName
        bid=self.bid
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/web-seller-affiliate/target_campaign'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        await asyncio.sleep(10)
        commissionId_list=set()
        p=1
        while True:
            api_url1=f'https://{self.host}/api/v3/affiliateplatform/gql?q=SearchTargetCampaignQuery'

            data={
                    "operationName":"SearchTargetCampaignQuery",
                    "query":"\n      query SearchTargetCampaignQuery($pageNum: Int, $pageSize: Int, $commissionId: Long, $commissionIdList: [Long!], $commissionName: String, $periodStartTime: Long, $periodEndTime: Long, $status: CommissionStatus, $affiliateTargetingList: [CommissionAffiliateScope!], $productId: Long, $productName: String, $scene: SearchTargetCampaignScene, $shopName: String, $shopType: CommissionSettingShopType, $affiliateId: Long, $affiliateScope: CommissionAffiliateScope, $commissionType: CommissionType, $commissionStatus: [CommissionStatus!], $needFreeSampleCount: Boolean) {\n        SearchTargetCampaign(\n          pageNum: $pageNum\n          pageSize: $pageSize\n          commissionId: $commissionId\n          commissionIdList: $commissionIdList\n          commissionName: $commissionName\n          periodStartTime: $periodStartTime\n          periodEndTime: $periodEndTime\n          status: $status\n          affiliateTargetingList: $affiliateTargetingList\n          productId: $productId\n          productName: $productName\n          scene: $scene\n          shopName: $shopName\n          shopType: $shopType\n          affiliateId: $affiliateId\n          affiliateScope: $affiliateScope\n          commissionType: $commissionType\n          commissionStatus: $commissionStatus\n          needFreeSampleCount: $needFreeSampleCount\n        ) {\n          pagination {\n            pageNum\n            pageSize\n            totalCount\n            needTotalCount\n          }\n          list {\n            commissionId\n            commissionName\n            periodStartTime\n            periodEndTime\n            status\n            commissionType\n            description\n            lastEditor\n            lastEditTime\n            shopId\n            shopName\n            isSetBudget\n            budget\n            budgetCost\n            commissionSource\n            affiliateTargeting\n            items {\n              name\n              id\n              image\n              rate\n            }\n            left\n            minRate\n            maxRate\n            setAllCategory\n            affiliateNum\n            itemList {\n              name\n              id\n              image\n              rate\n            }\n            itemCount\n            pendingTerminatedTime\n            terminatedTime\n            commissionFreeSample {\n              commissionId\n              freeSampleItemCount\n            }\n          }\n        }\n      }\n      ",
                    "variables":{"pageNum":p,"pageSize":20,"scene":"Default","needFreeSampleCount":True,"commissionStatus":["CommissionStatusOngoing","CommissionStatusUpcoming"]}
                }

            json_data=await plw_make_request(page,api_url1,data=data)
            if json_data:
                clist=json_data['data']['SearchTargetCampaign']['list']
                for citem in clist:
                    commissionId_list.add(citem['commissionId'])
                logging.info(f'店铺:《{dpName}》,{bid},第 {p} 页,获取 {len(clist)} 个达人计划,当前总数:{len(commissionId_list)}')
                if p==1:
                    totalCount=json_data['data']['SearchTargetCampaign']['pagination']['totalCount']
                    pageSize=json_data['data']['SearchTargetCampaign']['pagination']['pageSize']
                    max_p=math.ceil(totalCount/pageSize)
                    logging.info(f'店铺:《{dpName}》,{bid},共 {max_p} 页计划,总数量 {totalCount} 个')
                
                if p>=max_p:
                    break

                p+=1

        api_url2=f'https://{self.host}/api/v3/affiliateplatform/gql?q=TerminateTargetCampaign'
        for cj,cmid in enumerate(commissionId_list,start=1):

            data2={
                    
                    "operationName":"TerminateTargetCampaign",
                    "query":"\n      mutation TerminateTargetCampaign(\n        $commissionId: Long\n      ) {\n        TerminateTargetCampaign(\n          commissionId: $commissionId\n        ) {\n          isSuccess\n        }\n      }\n    ",
                    "variables":{"commissionId":cmid}
                }
            json_data2=await plw_make_request(page,api_url2,data=data2)
            logging.info(f'店铺:《{dpName}》,{bid},第 {cj} 个,执行删除结果:{json_data2}')


        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)

        return {'code':0,'msg':'执行成功','aff':1}

    async def yb_publish_bigdata(self):

        '''虾皮自动发布大数据'''
        basic_info=self.basic_info
        host=self.host
        dpName=self.dpName
        bid=self.bid
        country=basic_info['Country']
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
        lg_map={
            '印尼':'印尼语',
            '马来西亚':'英语',
            '泰国':'泰语',
            '新加坡':'英语'
        }
        cur_lg=lg_map[country]
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/product/list/live/all?operationSortBy=recommend_v2'  
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        await plw_wait_xpath(page,'//div[@class="list-page-header-title"]')

        el_add_btn= page.locator('xpath=//span[text()="Add a New Product"]/../../button[@id="top-add-new-product-btn" and contains(@class,"disabled")]')
        if (await el_add_btn.count())>0:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':0,'msg':'无法发布数据跳过','aff':0}

        suc=0
        t0=asyncio.create_task(plw_bring_to_front_if_needed(page))
        cur_time=time.time()
        set_day_range=10

        if country=='泰国':
            zd_dc_bid='th_dc_bid'
            zd_dc_shopid='th_dc_shopid'
            zd_is_dc='is_th_big_dc'
            zd_dctime='thdaochuTime'
            zd_del_count='th_del_count'

        elif country=='马来西亚':
            zd_dc_bid='ml_dc_bid'
            zd_dc_shopid='ml_dc_shopid'
            zd_is_dc='is_ml_big_dc'
            zd_dctime='mldaochuTime'
            zd_del_count='ml_del_count'
            zd_atc='ml_atc'

        elif country=='印尼':
            zd_dc_bid='distribution_export_bid'
            zd_dc_shopid='distribution_export_shopid'
            zd_is_dc='is_distribution_export'
            zd_dctime='daochuTime'
            zd_del_count='del_count'
            zd_atc='yn_atc'

        try:
            logging.info(f'店铺:《{dpName}》,{bid},第一步,删除 {set_day_range} 天无流量产品')
            itemid_has_pv,itemids_tow_atc=await plw_xp_get_pv(page,basic_info)
            if itemid_has_pv is None:
                logging.info(f'店铺:《{dpName}》,{bid},获取流量信息错误,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-3,'msg':'获取流量信息错误'}
            pro_list=await plw_xp_get_prolist(page,basic_info)
            if pro_list is None:
                logging.info(f'店铺:《{dpName}》,{bid},获取产品列表错误,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-4,'msg':'获取产品列表错误'}
            itemids_need_del=[]

            c10day_count=0
            c10day_nopv_count=0
            itemid_rcode_map={}
            itemid_1688_need_mark=[]
            for pro in pro_list:
                p_itemid=str(pro['id'])
                p_name=pro['name']
                p_1688_itemid=pro['parent_sku']
                rcode_mat= re.search(r'.*\|(.{8})\|$',p_name)
                rcode=rcode_mat.group(1) if rcode_mat else None
                itemid_rcode_map[p_itemid]=rcode
                p_create_time=pro['create_time']
                if p_itemid in itemids_tow_atc:
                    itemid_1688_need_mark.append(p_1688_itemid)
                    itemids_need_del.append(int(p_itemid))

                elif (cur_time-p_create_time) > set_day_range*86400:
                    c10day_count+=1
                    if p_itemid not in itemid_has_pv:
                        itemids_need_del.append(int(p_itemid))
                        c10day_nopv_count+=1
            itemid_1688_wstr=','.join([f"'{itemid}'" for itemid in itemid_1688_need_mark])
            aff_mark= self.ms.ExecNoQuery(f'update s1688pro set {zd_atc}=1 where itemid in ({itemid_1688_wstr})')
            logging.info(f'店铺:《{dpName}》,{bid},共 {len(pro_list)} 个在售产品,其中发布超过10天 {c10day_count} 个,发布超过10天且无流量 {c10day_nopv_count} 个,需删除 {len(itemids_need_del)} 个')
            logging.info(f'店铺:《{dpName}》,{bid},加购达标:{len(itemids_tow_atc)},需标记:{len(itemid_1688_need_mark)},实际标记:{aff_mark}')

            itemids_need_del=itemids_need_del[:40]
            for j in range(math.ceil(len(itemids_need_del)/48)):
                cur_itemid_list=itemids_need_del[j*48:(j+1)*48]
                res_del=await plw_xp_del_pro(page,basic_info,cur_itemid_list)
                cur_sjm_list=[]
                cur_has_del=[]
                aff_reset=0
                if res_del:
                    if res_del['code']==0:
                        del_list=res_del['data']['result']
                        for del_data in del_list:
                            if del_data['code']==0:
                                cur_has_del.append(str(del_data['id']))
                                if itemid_rcode_map.get(str(del_data['id'])):
                                    cur_sjm_list.append(itemid_rcode_map.get(str(del_data['id'])))
                        
                        if cur_sjm_list:
                            wstr=','.join([f"'{sjm}'" for sjm in cur_sjm_list])
                            aff_reset+=self.ms.ExecNoQuery(f'update s1688pro set {zd_del_count}={zd_del_count}+1 where random_code in ({wstr})')

                        logging.info(f'店铺:《{dpName}》,{bid},第 {j+1} 页,成功删除:{len(del_list)} 个产品,有随机码 {len(cur_sjm_list)}个,成功标记:{aff_reset}')                   

            logging.info(f'店铺:《{dpName}》,{bid},第二步,补充 40 个产品')
            can_count=await plw_get_can_publish(page,basic_info)
            if can_count==0:
                logging.info(f'店铺:《{dpName}》,{bid},可发布数量为0,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':0,'msg':'可发布数量为0','aff':0}

            need_publish_count=await plw_get_list_count(page,basic_info)
            if need_publish_count is None:
                logging.info(f'店铺:《{dpName}》,{bid},获取产品列表概错误,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-5,'msg':'获取产品列表概错误'}
            if need_publish_count>50:
                need_publish_count=50

            if need_publish_count >0:

                logging.info(f'店铺:《{dpName}》,{bid},需上架 {need_publish_count} 个产品')

                dcmr=await plw_get_excel_pro(page,basic_info,need_publish_count)
                if  dcmr is None:
                    logging.info(f'店铺:《{dpName}》,{bid},生成产品批量表错误,退出')
                    await page.close()
                    await plw.stop()
                    close_SunBrowser(bid,self.task_id)
                    return {'code':-6,'msg':'生成产品批量表错误'}

                if dcmr!=0:
                    purl=f'https://{host}/portal/product-mass/import/upload'
                    await plw_repeat_goto(page,purl)
                    sss=await plw_check_login(page,basic_info)
                    if not sss:
                        await page.close()
                        await plw.stop()
                        close_SunBrowser(bid,self.task_id)
                        return {'code':-2,'msg':'账户登录失败'}
                    
                    file_names=os.listdir(dcmr)

                    for j,file_name in enumerate(file_names,start=1):

                        file_path=os.path.join(dcmr,file_name)

                        logging.info(f'店铺:《{self.dpName}》,{self.bid},开始上传第 {j} 个文件:《{file_path}》')
                        upload_ipt=await plw_wait_xpath(page,'//input[@class="eds-file-uploader uploader eds-upload__input"]')
                        await upload_ipt.set_input_files(file_path)
                        await asyncio.sleep(5)

                    res_reports=await plw_xp_get_report(page,file_names,self.basic_info)
                    for fff_nnn,res_report in res_reports.items():
                        logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传结束')
                        rp_state='Successful'
                        file_id=res_report['id']
                        rp_status=res_report['record_status']
                        suc_count=res_report['success_count']
                        all_count=res_report['total_count']
                        handled_count=res_report['handled_count']
                        fail_count=all_count-suc_count
                        ctime=timestamp_to_sql_datetime(res_report['ctime'])
                        mtime=res_report['mtime']
                        if mtime!=0:
                            mtime=timestamp_to_sql_datetime(res_report['ctime'])
                        else:
                            mtime=None

                        shopid=res_report['shop_id']
                        
                        if suc_count==0:
                            rp_state='Unsuccessful'
                        if rp_status==7 or handled_count==0:
                            rp_state='Failed'
                        
                        c_file_p=os.path.join(dcmr,fff_nnn)
                        parentids=get_parentid_from_excel(c_file_p)
                        pstr=','.join([f"'{parentid}'" for parentid in parentids])
                        if rp_state!='Successful':
                            aff_reset_pid=self.ms.ExecNoQuery(f"update S1688Pro set {zd_dc_bid}=null where itemid in ({pstr})")
                            logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传失败,重置产品:{aff_reset_pid},')
                        else:
                            now_time=datetime.datetime.now()
                            aff_dc=self.ms.ExecNoQuery(f"update S1688Pro set {zd_is_dc}=1,{zd_dctime}=? where itemid in ({pstr})",(now_time,))
                            logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传成功,标记导出状态:{aff_dc}')
                            await asyncio.sleep(1)
                
            await asyncio.sleep(5)
            rs_qqc=self.ms.ExecQuery('select word_blacklist from Blacklist where word_language=?',(cur_lg,))
            qqc_list=[r[0] for r in rs_qqc]
            logging.info(f'店铺:《{dpName}》,{bid},第三步,草稿箱选择类目并上架,加载 {len(qqc_list)} 个{cur_lg}侵权词')

            await plw_repeat_goto(page,f'https://{host}/portal/product/list/unpublished/draft')
            sss=await plw_check_login(page,basic_info)
            if not sss:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-2,'msg':'账户登录失败'}
            await asyncio.sleep(10)
            # await plw_wait_xpath(page,'//div[@class="draft-product-list-table-row"]') 


            draft_list=await plw_xp_get_draftlist(page,basic_info)
 
            for dj,pro_draft_list in enumerate(draft_list[:50],start=1):
                ptit=pro_draft_list['name']
                d_itemid=pro_draft_list['id']
                d_pid=pro_draft_list['parent_sku']
                if not is_valid_name(ptit,qqc_list):
                    res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,标题包含侵权词跳过,标记删除:{res_del_ccc}')
                    continue
                quality_violation_result=pro_draft_list['quality_violation_result']
                if quality_violation_result>0:
                    res_del=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    aff_reset=0
                    if res_del:
                        if res_del['code']==0:
                            del_list=res_del['data']['result']
                            if del_list:
                                aff_reset=self.ms.ExecNoQuery('update s1688pro set is_wg=1 where itemid=?',(str(d_pid),))

                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,违规跳过,标记删除:{aff_reset}')
                    continue

                edit_url=f'https://{host}/portal/product/unpublished/{d_itemid}'
                #edit_url=f'https://seller.shopee.co.id/portal/product/{d_itemid}?pageEntry=product_list'
                await plw_repeat_goto(page,edit_url)
                sss=await plw_check_login(page,basic_info)
                if not sss:
                    await page.close()
                    await plw.stop()
                    close_SunBrowser(bid,self.task_id)
                    return {'code':-2,'msg':'账户登录失败'}
                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,开始发布...')

                await asyncio.sleep(3)
                el_tc=page.locator('//div[text()="Discard changes?"]/..//span[text()="Cancel"]')
                if (await el_tc.count()>0):
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,出现取消弹窗点击')
                    await el_tc.click(delay=200)
                    await asyncio.sleep(3)

                is_tc=False
                wait_lm=0
                while True:
                    el_select_category= page.locator('xpath=//div[@class="category-select-item"]')
                    if (await el_select_category.count())>0:
                        ebtn= el_select_category.nth(0).locator('xpath=./div[@class="category-select-radio"]/div[1]')
                        try:
                            await ebtn.click(delay=200)
                        except Exception as e:
                            print(e)
                    await asyncio.sleep(3)
                    el_clm=page.locator('xpath=//div[@class="product-category-text"]/span[1]')
                    try:
                        lmtxt=await el_clm.text_content()
                        if lmtxt !='Please set category':
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,成功选中类目')
                            break
                    except Exception as e:
                        print(e)
                    wait_lm+=1
                    if wait_lm>10:
                        is_tc=True
                        break
                if is_tc:
                    res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,无法选择类目,删除:{res_del_ccc}')
                    continue

                await asyncio.sleep(5)

                el_ipt_des=page.locator('xpath=//div[@componentkey="ProductDescriptionEditor"]//textarea[1]')
                if (await el_ipt_des.count())>0:

                    des_txt=await el_ipt_des.input_value()
                    is_chinese,replace_txt=remove_chinese(des_txt)
                    if is_chinese==1:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,描述出现中文,需替换')
                        await el_ipt_des.fill(replace_txt)
                        await asyncio.sleep(1)


                is_direct=True
                upload_img=page.locator('xpath=//span[@class="eds-radio__label" and text()="Image"]')
                is_not_size_img=False
                if (await upload_img.count())>0:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品,需补充尺码图')
                    is_direct=False
                    rs_1688=self.ms.ExecQuery(f'select image,images from s1688pro where itemid=?',(d_pid,))
                    if len(rs_1688)==0:
                        continue
                    size_img_url=rs_1688[0][0]
                    imgs=[]
                    if rs_1688[0][1]:
                        imgs=json.loads(rs_1688[0][1])
                    sssj=0
                    
                    while True:
                        try:
                            #img_url=size_img_url
                            img_url=f"http://155.94.192.2/cg/cjt/ImageProxy.aspx?url={size_img_url}"
                            res_img=requests.get(img_url,timeout=120)
                            if res_img.status_code==200:
                                imgcot=res_img.content
                                break
                            elif res_img.status_code==500:
                                sssj+=1
                                if sssj<len(imgs):
                                    size_img_url=imgs[sssj]
                                else:
                                    is_not_size_img=True
                                    break
                        except Exception as e:
                            print(e)
                            await asyncio.sleep(3)
                        
                    os.makedirs(f'临时尺码图',exist_ok=True)
                    characters = string.ascii_letters + string.digits
                    random_code = ''.join(random.choice(characters) for _ in range(4))
                    img_path=f'临时尺码图/{random_code}_{getTimeStr()}.jpg'
                    with open(img_path,'wb') as f:
                        f.write(imgcot)

                    el_select_img=page.locator('xpath=//span[@class="eds-radio__label" and text()="Image"]')
                    try:
                        await el_select_img.click(delay=200)
                        await asyncio.sleep(3)
                    except Exception as e:
                        traceback.print_exc()
                        print(e)
                        continue
                    upload_img=await plw_wait_xpath(page,'//div[@class="product-image-size-chart"]//input[@class="eds-upload__input"]')
                    await upload_img.set_input_files(img_path)
                    while True:
                        el_img_ck=page.locator('xpath=//div[@class="image-size-chart"]//div[@class="shopee-file-upload pic"]/div[1]')

                        try:
                            cstyle=await el_img_ck.get_attribute('style')
                        except Exception as e:
                            print(e)
                            break

                        if cstyle and 'background-image: url' in cstyle:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品,成功上传尺码图')
                            os.remove(img_path)
                            break
                        await asyncio.sleep(3)

                if is_not_size_img:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},无法填充尺码图跳过')
                    continue
                el_attribute_select_list=page.locator('xpath=//div[@class="mandatory"]/ancestor::div[@class="attribute-select-item"]')
                select_item_count=await el_attribute_select_list.count()
                if select_item_count==1:
                    await asyncio.sleep(3)
                    select_item_count=await el_attribute_select_list.count()
                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},共 {select_item_count} 项必填项,开始填写...')
                is_wait_opt_timeout=False #判断是否填写必填项超时
                for sj in range(select_item_count):
                    
                    el_row_tit=el_attribute_select_list.nth(sj).locator('xpath=.//div[@class="item-title"]/div[1]')
                    try:
                        speti_name=await el_row_tit.text_content(timeout=5000)
                    except Exception as e:
                        break
                    if 'Brand' in speti_name:
                        continue
                    is_direct=False
                    el_ipt=el_attribute_select_list.nth(sj).locator('xpath=.//input[1]')
                    if (await el_ipt.count()>0):
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》需填写输入框')
                        if 'Input Voltage' in speti_name:
                            await el_ipt.fill('220')

                        if 'TISI License Website' in speti_name:
                            await el_ipt.fill('NO')
                        
                        if 'TIS No' in speti_name:
                            await el_ipt.fill('NO')
                        continue

                    if 'Expiry Date' in speti_name:
                        # expiry_date=(datetime.date.today() + relativedelta(years=2)).strftime("%d/%m/%Y")
                        # el_date_div=el_attribute_select_list.nth(sj).locator('xpath=.//div[@class="eds-date-picker__input"]//div[@class="eds-selector__inner line-clamp--1"]')
                        # if (await el_date_div.count())>0:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性是日期属性特殊处理...')
                        #     await el_date_div.evaluate(f"el => el.textContent = '{expiry_date}'")
                        #     await asyncio.sleep(1)

                        is_wait_opt_timeout=True
                        break

                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》,开始填写')
                    el_xl=el_attribute_select_list.nth(sj).locator('xpath=./div[1]/div[2]//div[@class="eds-select"]')
                    #需填写有效期的操作



                    el_xl_btn=el_attribute_select_list.nth(sj).locator('xpath=./div[1]/div[2]//div[@class="eds-selector__suffix"]')

                    el_xl_ipt=el_xl.locator('xpath=.//div[contains(@class,"placeholder")]')

                    if (await el_xl_ipt.count())==0:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》已经预填写跳过...')
                        continue
                    
                    
                    is_mut=False
                    wait_opt=0
   
                    while True:
                        try:
                            await el_xl_btn.click(delay=200)
                        except Exception as e:
                            print(e)
                        el_opts=page.locator('xpath=//ul[@class="eds-dropdown-menu"]//div[@class="eds-option"]')
                        el_opts2=page.locator('xpath=//ul[@class="eds-dropdown-menu"]//div[@class="eds-option multiple"]')
                        if (await el_opts.count())>0:
                            break
                        if (await el_opts2.count())>0:
                            el_opts=el_opts2
                            is_mut=True
                            break
        
                        await asyncio.sleep(3)
                        wait_opt+=1
                        if wait_opt>10:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》填写超时退出')
                            is_wait_opt_timeout=True
                            break
                    
                    if is_wait_opt_timeout:
                        break
                    
                    is_select=False
                    for opj in range(await el_opts.count()):
                        el_copt=el_opts.nth(opj)
                        try:
                            el_txt=(await el_copt.text_content(timeout=10000)).lower()
                            #print(el_txt)
                        except Exception as e:
                            print(e)
                            break
                            

                        if el_txt.startswith('no') or el_txt.startswith('oth'):
                            try:
                                await el_copt.click(delay=200)
                                is_select=True
                                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性,选中:<{el_txt}>,退出')
                                break
                            except Exception as e:
                                print(e)
                                
                    if not is_select:

                        try:
                            await el_opts.nth(0).click(delay=200)
                        except Exception as e:
                            print(e)
                    
                    if is_mut:

                        try:
                            await el_xl_btn.click(delay=200)
                        except Exception as e:
                            print(e)

                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},必填项,填写完毕')

                await asyncio.sleep(1)
                if country=='马来西亚':
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},填写包裹体积...')
                    el_parcel=page.locator('xpath=//div[@data-auto-correct-key="dimension"]/div[@class="edit-row-right-full"]')
                    if (await el_parcel.count())>0:
                        el_width_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.width"]//input')
                        await el_width_ipt.fill('15')
                        await asyncio.sleep(1)
                        el_length_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.length"]//input')
                        await el_length_ipt.fill('20')
                        await asyncio.sleep(1)
                        el_high_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.height"]//input')
                        await el_high_ipt.fill('10')
                        await asyncio.sleep(1)
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},包裹体积填写完毕')
                        await asyncio.sleep(3)

                await asyncio.sleep(2)

                el_shipping=page.locator('xpath=//div[@class="product-shipping container"]//div[@class="grid optional-item"]//div[@class="eds-switch eds-switch--close eds-switch--normal"]')
                shipping_count=await el_shipping.count()
                if shipping_count>0 and country in ['马来西亚','泰国','越南'] :

                    el_first_shipping=el_shipping.nth(0)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},选择运费')
                    try:
                        await el_first_shipping.click(delay=200)
                        await asyncio.sleep(2)
                    except Exception as e:
                        print(e)
                    el_qr_btn=page.locator('xpath=//div[contains(., "Once this channel is enabled")]//button[1]')
                    if (await el_qr_btn.count())>0:
                        try:
                            await el_qr_btn.click(delay=200)
                            await asyncio.sleep(2)
                        except Exception as e:
                            print(e)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},成功选中第一个运费')
                await asyncio.sleep(3)

                if is_wait_opt_timeout:
                    res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},等待超时,删除:{res_del_ccc}')
                    continue
                el_publist=page.locator('xpath=//span[text()="Publish"]')
                try:
                    await el_publist.click(delay=200)
                except Exception as e:
                    res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},点击publish错误,删除:{res_del_ccc} ')

                wait_publish=0
                tzq=0
                while True:
                    try:
                        cot=await page.content()
                        if ('Product has been successfully published' in cot) or ('Listed successfully!' in cot) or '/portal/product/list/unpublished/draft' in page.url :
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},成功发布,剩余:{len(draft_list)-dj} 个产品')
                            if is_direct:
                                aff_lmm=self.ms.merge_into('ShopeeDCateGory',['itemid','offerid','leimu'],[str(d_itemid),str(d_pid),lmtxt],['leimu'],True)
                                logging.info(f'店铺:《{dpName}》,{bid},记录类目:《{lmtxt}》:{aff_lmm}')
                            break
                        
                        
                        if 'Cannot create product because the shop is under penalty' in cot:

                            await page.close()
                            await plw.stop()
                            close_SunBrowser(bid,self.task_id)

                            return {'code':0,'msg':'店铺受到惩罚','aff':0}

                                
                        
                        el_save_publish=page.locator('//div[text()="Are you sure to Save and Publish ?"]/../../..//span[text()="Save and Publish"]')

                        if (await el_save_publish.count())>0:
                            try:
                                await el_save_publish.click(delay=200)
                                await asyncio.sleep(1)
                            except Exception as e:
                                print(e)
                    except Exception as e:
                        print(e)

                    await asyncio.sleep(1)
                    wait_publish+=1
                    tzq+=1
                    if wait_publish>21:
                        res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},发布超时失败,删除:{res_del_ccc},剩余:{len(draft_list)-dj} 个产品')
                        break

                    if tzq==20:
                        el_publist=page.locator('xpath=//span[text()="Publish"]')
                        try:
                            await el_publist.click(delay=200)
                        except Exception as e:
                            print(e)

                        tzq=0
            
                await asyncio.sleep(3)
                        

            return_res={'code':0,'msg':'执行成功','aff':suc}

        except Exception as e:
            traceback.print_exc()
            logging.error(e)
            return_res={'code':-3,'msg':str(e)}

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_del_draft(self):

        '''删除草稿箱所有产品'''
        basic_info=self.basic_info
        host=self.host
        dpName=self.dpName
        country=basic_info['Country']
        cur_zd_cs=Country_Sql_Zd_Map[country]
        zd_dc_bid=cur_zd_cs['zd_dc_bid']
        zd_dc_shopid=cur_zd_cs['zd_dc_shopid']
        zd_is_dc=cur_zd_cs['zd_is_dc']
        bid=self.bid
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/product/list/unpublished/draft'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        await asyncio.sleep(10)
        draft_list=await plw_xp_get_draftlist(page,basic_info)
        itemid_parent_map={str(dpro['id']):str(dpro['parent_sku']) for dpro in draft_list}

        for j in range(math.ceil(len(draft_list)/100)):
            cur_draft_list=draft_list[j*100:(j+1)*100]
            cur_itemids=[cdpro['id'] for cdpro in cur_draft_list]
            res_del=await plw_xp_del_draftpro(page,basic_info,cur_itemids)
            cur_has_del=[]
            cur_parent_list=[]
            aff_reset=0
            if res_del:
                if res_del['code']==0:
                    del_list=res_del['data']['result']
                    for del_data in del_list:
                        if del_data['code']==0:
                            cur_has_del.append(str(del_data['unpublished_id']))
                            if itemid_parent_map.get(str(del_data['unpublished_id'])):
                                cur_parent_list.append(itemid_parent_map.get(str(del_data['unpublished_id'])))
                    
                    if cur_parent_list:
                        wstr=','.join([f"'{sjm}'" for sjm in cur_parent_list])
                        aff_reset+=self.ms.ExecNoQuery(f'update s1688pro set {zd_is_dc}=0,{zd_dc_shopid}=null,{zd_dc_bid}=null where itemid in ({wstr})')
                    logging.info(f'店铺:《{dpName}》,{bid},第 {j+1} 页,成功删除:{len(del_list)} 个产品,可标记 {len(cur_parent_list)}个,成功标记:{aff_reset}')   
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)

        return {'code':0,'msg':'执行成功','aff':1}

    async def yb_del_draft2(self):

        '''删除草稿箱所有产品'''
        basic_info=self.basic_info
        host=self.host
        dpName=self.dpName
        bid=self.bid
        country=basic_info['Country']
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/product/list/unpublished/draft'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        await asyncio.sleep(10)
        draft_list=await plw_xp_get_draftlist(page,basic_info)
        itemid_parent_map={}
        for ddd in draft_list:
            d_itemid=str(ddd['id'])
            p_name=ddd['name']
            rcode_mat= re.search(r'.*\|(.{8})\|$',p_name)
            rcode=rcode_mat.group(1) if rcode_mat else None
            itemid_parent_map[d_itemid]=rcode

        for j in range(math.ceil(len(draft_list)/100)):
            cur_draft_list=draft_list[j*100:(j+1)*100]
            cur_itemids=[cdpro['id'] for cdpro in cur_draft_list]

            res_del=await plw_xp_del_draftpro(page,basic_info,cur_itemids)
            cur_has_del=[]
            cur_parent_list=[]
            aff_reset=0
            if res_del:
                if res_del['code']==0:
                    del_list=res_del['data']['result']
                    for del_data in del_list:
                        if del_data['code']==0:
                            cur_has_del.append(str(del_data['unpublished_id']))
                            if itemid_parent_map.get(str(del_data['unpublished_id'])):
                                cur_parent_list.append(itemid_parent_map.get(str(del_data['unpublished_id'])))
                    if cur_parent_list:
                        wstr=','.join([f"'{sjm}'" for sjm in cur_parent_list])
                        aff_reset+=self.ms.ExecNoQuery(f"update ShopeeAdsMove set is_draft=0 where to_country='{country}' and random_code in ({wstr})")
                    logging.info(f'店铺:《{dpName}》,{bid},第 {j+1} 页,成功删除:{len(del_list)} 个产品,可标记 {len(cur_parent_list)}个,成功标记:{aff_reset}')   
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)

        return {'code':0,'msg':'执行成功','aff':1}

    async def yb_cteate_ad(self):
        '''发布广告'''
        bid=self.bid
        bname=self.dpName
        basic_info=self.basic_info
        host=self.host
        country=basic_info['Country']
        max_count=basic_info['ads_target_quantity']
        target_count=20
        suc=0
        if not max_count:
            max_count=100
        else:
            target_count=max_count
        

        
        if country=='印尼':
            daily_budget='10000'
            target_ROAS='10'
        elif country=='泰国':
            daily_budget='40'
            target_ROAS='10'
        
        elif country=='马来西亚':
            daily_budget='8'
            target_ROAS='10'
        
        elif country=='菲律宾':
            daily_budget='40'
            target_ROAS='10'
        
        elif country=='越南':
            daily_budget='20000'
            target_ROAS='10'
        
        elif country=='台湾':
            daily_budget='30'
            target_ROAS='10'
                
        elif country=='新加坡':
            daily_budget='4'
            target_ROAS='10'
        
        elif country=='巴西':
            daily_budget='6'
            target_ROAS='10'


        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()
        t0=asyncio.create_task(plw_bring_to_front_if_needed(page))
        url=f'https://{host}/portal/marketing/pas/product/create?source_page_id=1'
        if basic_info['is_KJ']==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})

        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}

        await asyncio.sleep(3)
        ad_cre_list=await plw_update_CreAD_Task(page,basic_info,'执行成功','前')
        
        if ad_cre_list is None:
            await plw_update_CreAD_Task(page,basic_info,'执行成功','后')
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-3,'msg':'获取广告信息错误'}
        elif len(ad_cre_list)==0:
            await plw_update_CreAD_Task(page,basic_info,'执行成功','后')
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':0,'msg':'无新产品','aff':0}
        else:
            rw_msg='执行成功'
            need_create_count=len(ad_cre_list) if len(ad_cre_list)<target_count else target_count
            for j in range(1,need_create_count+1):
                if j!=1:
                    await plw_repeat_goto(page,url)
                    sss=await plw_check_login(page,basic_info)
                    if not sss:
                        await page.close()
                        await plw.stop()
                        close_SunBrowser(bid,self.task_id)
                        return {'code':-2,'msg':'账户登录失败'}
                    
                logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,第一步,跳转到广告发布页面...')
                await asyncio.sleep(5)

                logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,第二步,开始设置广告预算...')
                radio_btns=await plw_wait_xpath(page,'//div[@class="budget-input-container"]//label[@class="eds-radio yes-limit"]')
                await asyncio.sleep(3)
                await radio_btns.hover()
                await asyncio.sleep(3)
                await radio_btns.click(delay=200)
                await asyncio.sleep(3)
                el_input=await plw_wait_xpath(page,'//div[@class="budget-input-container"]//input[@class="eds-input__input"]')
                await el_input.fill(daily_budget)
                await asyncio.sleep(2)

                logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,第三步,Product Selection...')
                elps1=page.locator('xpath=//div[text()="Manually select products"]/..')
                if (await elps1.count())==0:
                    elps1=page.locator('xpath=//div[text()="手动选择商品"]/..')
                await elps1.click(delay=200)
                await asyncio.sleep(3)

                logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,第四步,开始添加产品...')
                await page.click('.add-product-btn',delay=200)
                await asyncio.sleep(10)
                await plw_wait_xpath(page,'//table[@class="eds-table__header"]')
                select_tr=None
                cur_itemid=str(ad_cre_list[j-1]['item_id'])
                await plw_wait_xpath(page,'//tr[contains(@class,"eds-table__row")]')
                while True:
                    try:
                        el_num=page.locator('xpath=//span[@class="nums"]/span[1]')
                        num_txt = await el_num.text_content()

                        el_th_ckall= page.locator('xpath=//div[@class="product-selector-modal"]//thead//th[1]//label[1]')
                        if num_txt.strip()!='0':
                            logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,当前自动选中数量:{num_txt},点击全选取消')
                            await el_th_ckall.click(delay=200)
                            
                        else:
                            logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,成功取消自动选择的产品')
                            break
                    except Exception as e:
                        print(e)
                    await asyncio.sleep(2)

                while True:

                    try:
                        el_serarch=page.locator('xpath=//div[@class="eds-input-group product-searcher"]/span[1]/div[1]')
                        await el_serarch.click(delay=200)
                        await asyncio.sleep(1)
                        el_select_list=page.locator('xpath=//div[@class="eds-option" and text()="Product ID"]')
                        if (await el_select_list.count())==0:
                            el_select_list=page.locator('xpath=//div[@class="eds-option" and text()="商品编号"]')
                        if (await el_select_list.count())>0:
                            await el_select_list.click(delay=200)
                            await asyncio.sleep(3)
                        
                        el_search_txt=page.locator('xpath=//div[@class="eds-input-group product-searcher"]/span[1]/div[1]/div[1]/div[text()="Product ID"]')
                        el_search_txt2=page.locator('xpath=//div[@class="eds-input-group product-searcher"]/span[1]/div[1]/div[1]/div[text()="商品编号"]')
                        if (await el_search_txt.count()) or (await el_search_txt2.count()):
                            logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,成功选择pid搜索框')
                            break

                    except Exception as e:
                        print(e)
                    await asyncio.sleep(1)
                                
                logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,itemid:{cur_itemid},开始搜索itemid...')

                is_timeout_search=False
                wait_search=0
                while True:
                    try:
                        el_ipt_itemid=page.locator('xpath=//div[@data-testid="product-selector-modal-search-input-content"]//input')
                        await el_ipt_itemid.fill(cur_itemid)
                        await asyncio.sleep(2)
                        await page.keyboard.press('Enter')
                        await asyncio.sleep(5)
                        trs=page.locator('xpath=//tr[contains(@class,"eds-table__row")]')
                        el_pid=trs.nth(0).locator('xpath=.//p[@class="id-ratings"]')
                        pid_txt = await el_pid.text_content()
                        print(pid_txt)
                        if cur_itemid in pid_txt:
                            logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,itemid:{cur_itemid},成功搜索到产品...')
                            jccc3=trs.nth(0).locator('xpath=.//a[@class="existing-ads-text"]')
                            if (await jccc3.count())==0:
                                select_tr=trs.nth(0)
                            break
                        wait_search+=7

                    except Exception as e:
                        print(e)
                    
                    await asyncio.sleep(1)
                    wait_search+=1

                    if wait_search>60:
                        is_timeout_search=True
                        logging.info(f'店铺《{bname}》,{bid},第 {j} 个广告,itemid:{cur_itemid},搜索超时退出')
                        break
                
                if is_timeout_search:
                    continue
                
                if not select_tr:
                    continue
                
                
                btn_stb=select_tr.locator('xpath=.//span[@class="eds-checkbox__indicator"]')
                await btn_stb.click(delay=200)
                await asyncio.sleep(1)
                el_footbtndivs=page.locator('xpath=//div[@class="eds-modal__footer-buttons"]')
                qr_count=await el_footbtndivs.count()
                for elfj in range(qr_count):
                    try:
                        el_btnqr=el_footbtndivs.nth(elfj).locator('xpath=./button[2]')
                        if (await el_btnqr.count())>0:
                            await el_btnqr.click(delay=200)
                            await asyncio.sleep(0.5) 
                    except Exception as e:
                        logging.error(e)
                await asyncio.sleep(3)



                logging.info(f'店铺《{bname}》,{bid},第五步,设置Target Roars')
                await page.evaluate("window.scrollBy(0, 200)")
                await asyncio.sleep(3)
                await page.evaluate("window.scrollBy(0, 200)")
                while True:
                    try:
                        el_target_roars=page.locator('xpath=//div[@class="radio-label" and text()="GMV Max Custom ROAS "]/../../span[@class="eds-radio__indicator"]')
                        if (await el_target_roars.count())==0:
                            el_target_roars=page.locator('xpath=//div[@class="text-title" and text()="GMV Max Custom ROAS"]')
                            if (await el_target_roars.count())==0:
                                el_target_roars=page.locator('xpath=//div[@class="text-title" and text()="全站推广自定义广告回报率（ROAS）"]')
                        
                        await el_target_roars.click(delay=200)
                        await asyncio.sleep(3)
                    
                    except Exception as e:
                        print(e)
                    
                    el_ppp=page.locator('xpath=//div[text()="Target ROAS"]/ancestor::div[@class="gmv-container"]//div[@class="eds-table__body-container"]')
                    if (await el_ppp.count())==0:
                        el_ppp=page.locator('xpath=//div[text()="目标ROAS"]/ancestor::div[@class="gmv-container"]//div[@class="eds-table__body-container"]')


                    if (await el_ppp.count())>0:
                        break
                    await asyncio.sleep(1)
                
                el_rapid_boost= el_ppp.locator('xpath=.//tr[1]/td[4]//div[@class="eds-switch eds-switch--open eds-switch--small"]')
                if (await el_rapid_boost.count())>0:
                    try:
                        await el_rapid_boost.hover()
                        await el_rapid_boost.click(delay=200)
                        await asyncio.sleep(3)
                    except Exception as e:
                        print(e)

                await asyncio.sleep(3)

                el_ipt_edit= el_ppp.locator('xpath=.//tr[1]/td[2]//div[@class="eds-popover__ref"]')

                el_cvalue= el_ppp.locator('xpath=.//tr[1]/td[2]//span[@class="roi-value"]')

                while True:
                    
                    cur_roars_value=await el_cvalue.text_content()

                    logging.info(f'店铺《{bname}》,{bid},当前Target ROAS:{cur_roars_value}')

                    if cur_roars_value=='10' or cur_roars_value=='10.0':
                        logging.info(f'店铺《{bname}》,{bid},Target ROAS,已设置为10')
                        break

                    try:
                        await el_ipt_edit.nth(0).click(delay=200)
                        await asyncio.sleep(3)

                    except Exception as e:
                        print(e)
                    
                    el_form=page.locator('xpath=//div[text()="ROAS Target"]/ancestor::form[1]')
                    if (await el_form.count())==0:
                        el_form=page.locator('xpath=//div[text()="目标ROAS" and @class="roi-edit-popover-title"]/ancestor::form[1]')       

                    el_set_value=el_form.nth(0).locator('xpath=.//span[text()="Set a value"]')
                    if (await el_set_value.count())==0:
                        el_set_value=el_form.nth(0).locator('xpath=.//span[text()="自定义目标值"]')

                    await el_set_value.click(delay=200)
                    await asyncio.sleep(3)

                    el_roars_ipt=el_set_value.locator('xpath=./..//input[1]')
                    await el_roars_ipt.fill(target_ROAS)
                    await asyncio.sleep(3)

                    # 向下滚动 200 像素
                    await page.evaluate("window.scrollBy(0, 200)")
                    # 向上滚动 100 像素
                    await page.evaluate("window.scrollBy(0, -100)")

                    el_btn_confirm= el_form.locator('xpath=.//span[text()="Confirm"]')
                    if (await el_btn_confirm.count())==0:
                        el_btn_confirm=el_form.locator('xpath=.//span[text()="确认"]')
                    await el_btn_confirm.click(delay=200)
                    await asyncio.sleep(3)

                await asyncio.sleep(3)

                logging.info(f'店铺《{bname}》,{bid},第六步,提交广告')
                el_footbtndivs=page.locator('xpath=//div[@class="bottom-container"]')
                el_btnqr=el_footbtndivs.nth(0).locator('xpath=./button[2]')
                await el_btnqr.click(delay=200)
                wait_pub=0
                is_jia_qi=False
                while True:
                    try:
                        cot=await page.content()
                        if 'ps_cannot_use_marketing_center_of_in_vacation_mode_label' in cot:
                            is_jia_qi=True
                            break
                        if 'Something went wrong. Please try again' in cot:
                            is_jia_qi=True
                            break

                    except Exception as e:
                        logging.error(e)
                    wait_pub+=1
                    await asyncio.sleep(1)
                    if wait_pub>=15:
                        break

                if is_jia_qi:
                    logging.info(f'店铺:《{self.dpName}》,{self.bid},处于假期模式退出广告创建')
                    rw_msg='假期模式'
                    break
                logging.info(f'店铺《{self.dpName}》,{bid},第 {j} 个广告,成功发布')
                suc+=1

        await plw_update_CreAD_Task(page,self.basic_info,rw_msg)
        #await update_all_adtype(page,self.basic_info)

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return {'code':0,'msg':'执行成功','aff':suc}
    
    async def yb_cj_pro_performance(self):
        '''采集大数据流量报表'''
        bid=self.bid
        bname=self.dpName
        basic_info=self.basic_info
        host=self.host
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/datacenter/product/performance'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        del_count=0
        try:
            await plw_wait_xpath(page,'//div[@class="cell" and (text()="Product Information" or text()= "商品")]')
            suc=0
            

            logging.info(f'店铺:《{bname}》,{bid},当前时间段开始采集当日报表数据...')
            pro_real_bb_list=await plw_xp_get_pro_performance(page,basic_info,'r')
            suc+=upload_performance(basic_info,pro_real_bb_list,'r')

            logging.info(f'店铺:《{bname}》,{bid},当开始采集昨日报表数据..')
            pro_real_bb_list=await plw_xp_get_pro_performance(page,basic_info,'y')
            suc+=upload_performance(basic_info,pro_real_bb_list,'y')
            
            logging.info(f'店铺:《{bname}》,{bid},当开始采集七天报表数据..')
            pro_real_bb_list=await plw_xp_get_pro_performance(page,basic_info,'w')
            suc+=upload_performance(basic_info,pro_real_bb_list,'w')

            logging.info(f'店铺:《{bname}》,{bid},当开始采集三十天报表数据..')
            pro_real_bb_list=await plw_xp_get_pro_performance(page,basic_info,'m')
            suc+=upload_performance(basic_info,pro_real_bb_list,'m')

            # rs_need_del=tms.ExecQuery('select itemid from ShopeeAdsPaesed where is_del_pro=1 and bid=?',(self.bid))
            # del_count=0
            # need_del_itemid = [rdd[0] for rdd in rs_need_del]
            # for pro_bb in pro_real_bb_list:
            #     if pro_bb['display_tag_label']=='psd_label_deleted':
            #         continue
            #     cur_itemid=str(pro_bb['id'])

            #     if cur_itemid in need_del_itemid:
            #         res_del_pro=await plw_xp_del_pro(page,basic_info,[int(cur_itemid)])
            #         if res_del_pro and res_del_pro['code']==0 and res_del_pro['data']['result'][0]['code']==0:
            #             del_count+=1
            #             logging.info(f'店铺:《{bname}》,{bid},itemid:{cur_itemid},广告成功删除产品')
            #         else:
            #             logging.info(f'店铺:《{bname}》,{bid},itemid:{cur_itemid},广告删除产品失败')
            
            # logging.info(f'店铺:《{bname}》,{bid},需删除:{len(rs_need_del)},成功删除:{del_count}')
            return_res={'code':0,'msg':'执行成功','aff':suc}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':-2,'msg':'执行出错'}

            
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_cj_ROAS(self):
        '''采集平台推荐ROARS'''
        bid=self.bid
        bname=self.dpName
        basic_info=self.basic_info
        host=self.host
        yybm=self.yybm
        country=basic_info['Country']
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/marketing/pas/product/create?source_page_id=1'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)

        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}

        need_get=0
        suc=0
        try:
            await plw_wait_xpath(page,'//span[@class="title-text" and text()="Product Selection "]')
            pro_bb_list=await plw_xp_get_pro_performance(page,basic_info,'m')
            
            for bj,bitem in enumerate(pro_bb_list,start=1):
                if bitem['display_tag_label']=='psd_label_deleted':
                    continue
                if bitem['add_to_cart_buyers']>=1 and bitem['uv_to_add_to_cart_rate']>=0.1:
                    itemid=bitem['id']
                    ptit=bitem['name']
                    cur_img=bitem['image']
                    if host=='seller.shopee.co.id':
                        cur_img=f'https://down-id.img.susercontent.com/file/{cur_img}'
                    elif host=='seller.shopee.co.th':
                        cur_img=f'https://cf.shopee.co.th/file/{cur_img}'
                    random_code=None
                    need_get+=1
                    mat=re.search(r'.*\|(.{8})\|$',ptit)
                    if mat:
                        random_code=mat.group(1)
                    res_roas=await plw_xp_get_reROAS(page,basic_info,itemid)
                    if not res_roas:
                        logging.info(f'店铺:《{bname}》,{bid},第 {bj} 个itemid:{itemid},获取系统推荐ROAS失败,跳过...')
                        continue
                    l_roas,e_roas,u_roas=res_roas
                    is_del=0
                    if bitem['add_to_cart_buyers']>=3:
                        res_del=await plw_xp_del_pro(page,basic_info,[itemid])
                        if res_del:
                            if res_del['code']==0:
                                del_list=res_del['data']['result']
                                for del_data in del_list:
                                    if del_data['code']==0:
                                        if str(del_data['id'])==str(itemid):
                                            is_del=1


                    bdata={
                        'Country':country,
                        'Platform':host,
                        'ItemID':str(itemid),
                        'ptitle':ptit,
                        'pic':cur_img,
                        'random_code':random_code,
                        'lower_ROARS':l_roas,
                        'exact_ROARS':e_roas,
                        'upper_ROARS':u_roas,
                        'bid':bid,
                        'bname':bname,
                        'yybm':yybm,
                        'is_del':is_del
                    }
                    zds=list(bdata.keys())
                    paras=list(bdata.values())
                    aff=self.ms.merge_into('ShopeeROARS',zds,paras,['itemid'],True)
                    logging.info(f'店铺:《{bname}》,{bid},第 {bj} 个itemid:{itemid},符合采集ROAS条件,采集状态:{aff},是否下架:{is_del}')
                    suc+=aff
            logging.info(f'店铺:《{bname}》,{bid},共 {len(pro_bb_list)} 个报表数据,需采集 {need_get} 个ROAS,成功采集 {suc} 个')
                
            return_res={'code':0,'msg':'执行成功','aff':suc}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':0,'msg':f'执行出错{e}'}

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_cj_adbb(self):
        '''采集广告报表'''
        bid=self.bid
        bname=self.dpName
        basic_info=self.basic_info
        host=self.host
        country=basic_info['Country']
        dqsq=SQ_Map.get(country)
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()
        #t0=asyncio.create_task(plw_check_pass(page,basic_info))
        st_time_sq8,ed_time_sq8=get_shopee_timestamp('today',8)
        url=f'https://{host}/portal/marketing/pas/index?from={st_time_sq8}&to={ed_time_sq8}&type=new_cpc_homepage&group=today'
        if self.iskj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})

        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        try:

            await plw_wait_xpath(page,'//span[text()="Export Data " or text()="导出数据 "]')
            await asyncio.sleep(3)
            suc=0
            period_range_list=['yesterday','last_week','last_month','last_three_month']

            for period_range in period_range_list:
   
                # rs=self.ms.ExecQuery('select count(*) from ShopeeAdsReport where dtype=? and bid=? and DATEDIFF(HOUR, update_time, GETDATE()) < 2',(period_range,bid))
                # if rs[0][0]>0:
                #     logging.info(f'店铺:《{bname}》,{bid},《{period_range}》今日已采集过,跳过')
                #     continue
                logging.info(f'店铺:《{bname}》,{bid},开始采集《{period_range}》广告报表数据...')
                pro_real_bb_list=await plw_xp_get_adbb(page,basic_info,period_range,'ongoing')
                if pro_real_bb_list is not None:
                    suc+=upload_adbb(basic_info,pro_real_bb_list,period_range)
                
            # yesterdat_date=get_yesterday_date_tz(dqsq)
            # rs_has_get=self.ms.ExecQuery('select distinct campaign_id from ShopeeAdsReport where dtype=? and data_date=? and bid=?',('today',yesterdat_date,bid))
            # has_get_camp_ids=[r[0] for r in rs_has_get]
            # pro_need_get_time_bb=[]
            # for pro_bb in pro_real_bb_list:
            #     campaign=pro_bb['campaign']
            #     cur_campaign_id=str(campaign['campaign_id'])
            #     if cur_campaign_id not in has_get_camp_ids:
            #         pro_need_get_time_bb.append(pro_bb)
            # logging.info(f'店铺:《{bname}》,{bid},共 {len(pro_real_bb_list)} 个广告,已采集区间报表:{len(has_get_camp_ids)},需采集:{len(pro_need_get_time_bb)}')
            # return_res=await self.yb_get_time_graph(page,pro_need_get_time_bb)

            return_res={'code':0,'msg':'执行成功','aff':suc}
        
        except Exception as e:
            traceback.print_exc()
            return_res={'code':-3,'msg':'执行出错'}

            
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_stop_testad(self):

        '''暂停测品广告'''
        bid=self.bid
        bname=self.dpName
        basic_info=self.basic_info
        host=self.host
        country=self.basic_info['Country']

        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/marketing/pas/index'
        if self.iskj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})
        cpc_map={
            '泰国':1.5,
            '马来西亚':0.15,
            '越南':750
        }
        if country=='印尼':

            cost_30day_list=[4000,8000,12000]
            
        elif country=='泰国':
            cost_30day_list=[6,12,18]

        elif country=='马来西亚':
            cost_30day_list=[1.20,2.40,3.60]
        
        elif country=='越南':
            cost_30day_list=[7000,14000,21000]


        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        try:

            await plw_wait_xpath(page,'//span[text()="Export Data " or text()="导出数据 "]')
       
            ad_bb_list=await plw_xp_get_adbb(page,basic_info,'last_month',state='ongoing')
            if ad_bb_list is None:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-3,'msg':'获取广告报表失败'}
            
            ll_bb_list=await plw_xp_get_pro_performance(page,basic_info,'m')
            if ll_bb_list is None:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-3,'msg':'获取流量报表失败'}
            
            itemid_cart_map={str(llitem['id']):[llitem['add_to_cart_buyers'],llitem['uv_to_add_to_cart_rate']] for llitem in ll_bb_list}
            aff_bb_save=upload_adbb(basic_info,ad_bb_list,'last_month')
            logging.info(f'店铺:《{bname}》,{bid},共获取 {len(itemid_cart_map.keys())} 个加购数据,存日 {aff_bb_save} 个广告报表数据')

            # with open(f'测试数据/aaa.json','w',encoding='utf-8') as f:

            #     json.dump(itemid_cart_map,f,ensure_ascii=False)
            
            need_paused_count=0
            need_delpro_count=0
            suc_pause=0
            suc_del=0

            itemid_atc_bdb=[]
            itemid_atc_db=[]
            itemid_atc_rate=[]
            itemid_ctr=[]

            for aj,aditem in enumerate(ad_bb_list,start=1):
                cur_itemid=str(aditem['manual_product_ads']['item_id'])
                cur_campid=aditem['campaign']['campaign_id']
                cur_pname=aditem['title']
                adrpt=aditem['report']
                cur_random_code=None
                mat=re.search(r'.*\|(.{8})\|$',cur_pname)
                if mat:
                    cur_random_code=mat.group(1)

                if aditem['state']!='ongoing':
                    #logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告停用跳过')
                    continue

                action_pause_ad=False
                action_del_pro=False
                is_jl=False
                add_to_cart_buyers=None
                uv_to_add_to_cart_rate=None
                action_txt=''

                cost=aditem['report']['cost']/100000
                impression=adrpt['impression']
                ctr=adrpt['ctr']
                click=adrpt['click']
                ad_strat_time=aditem['campaign']['start_time']
                ctime=int(time.time())
                
                if ctime-ad_strat_time>86400*10:
                    is_jl=True
                    action_pause_ad=True
                    action_del_pro=True
                    need_paused_count+=1
                    need_delpro_count+=1
                    action_txt='产品广告创建超过10天'

                elif click and cost/click>cpc_map[country]:
                    is_jl=True
                    action_pause_ad=True
                    action_del_pro=True
                    need_paused_count+=1
                    need_delpro_count+=1
                    action_txt=f'平均点击费用:{cost/click:.2f}>{cpc_map[country]}'

                elif impression>100 and ctr<0.03:
                    is_jl=True
                    action_pause_ad=True
                    action_del_pro=True
                    need_paused_count+=1
                    need_delpro_count+=1
                    action_txt=f'impression:{impression},ctr:{ctr*100:.2f}%,不达标条件'
                    itemid_ctr.append(cur_itemid)

            

                elif itemid_cart_map.get(cur_itemid):
     
                    add_to_cart_buyers,uv_to_add_to_cart_rate=itemid_cart_map[cur_itemid]
                    if add_to_cart_buyers>=3:
                        is_jl=True
                        action_pause_ad=True
                        need_paused_count+=1
                        action_txt=f'加购数量:{add_to_cart_buyers},超过3个用户,暂停广告'

                    else:
                        if cost_30day_list[0]<=cost<cost_30day_list[1]:
                            if not (uv_to_add_to_cart_rate>=0.1 and add_to_cart_buyers>=1):
                                is_jl=True
                                action_pause_ad=True
                                action_del_pro=True
                                need_paused_count+=1
                                need_delpro_count+=1
                                action_txt=f'Expense_30合计:{cost},不达标广告加购率({uv_to_add_to_cart_rate})>=10% 且 广告加购数量({add_to_cart_buyers})>=1'
                                itemid_atc_bdb.append(cur_itemid)

                        elif cost_30day_list[1]<=cost<cost_30day_list[2]:

                            if not (uv_to_add_to_cart_rate>=0.1 and add_to_cart_buyers>=2):
                                is_jl=True
                                action_pause_ad=True
                                action_del_pro=True
                                need_paused_count+=1
                                need_delpro_count+=1
                                action_txt=f'Expense_30合计:{cost},不达标广告加购率({uv_to_add_to_cart_rate})>=10% 且 广告加购数量({add_to_cart_buyers})>=2'
                                itemid_atc_bdb.append(cur_itemid)

                        elif cost>=cost_30day_list[2]:
                            is_jl=True
                            action_pause_ad=True
                            need_paused_count+=1
                            action_txt=f'Expense_30合计:{cost},达标广告加购率({uv_to_add_to_cart_rate})>=10% 且 广告加购数量({add_to_cart_buyers})>=3'

                            if not (uv_to_add_to_cart_rate>=0.1 and add_to_cart_buyers>=3):
                                action_del_pro=True
                                need_delpro_count+=1
                                action_txt=f'Expense_30合计:{cost},不达标广告加购率({uv_to_add_to_cart_rate})>=10% 且 广告加购数量({add_to_cart_buyers})>=3'
                                itemid_atc_bdb.append(cur_itemid)
                            else:
                                itemid_atc_db.append(cur_itemid)

                        else:
                            if (
                                (10<=click<20 and add_to_cart_buyers<1) 
                                or (20<=click<30 and add_to_cart_buyers<2)
                                or (30<=click<40 and add_to_cart_buyers<3)
                                or (click>=40 and add_to_cart_buyers<4)
                            ):
                                is_jl=True
                                action_pause_ad=True
                                action_del_pro=True
                                need_paused_count+=1
                                need_delpro_count+=1
                                action_txt=f'click:{click},add_to_cart_buyers:{add_to_cart_buyers},不达标条件'
                                itemid_atc_rate.append(cur_itemid)                            

                is_del_pro=0
                is_pause_ad=0
                
                if action_pause_ad:
                    res_paused_ad=await plw_xp_pause_ad(page,basic_info,[cur_campid])
                    if res_paused_ad and res_paused_ad['code']==0:
                        is_pause_ad=1
                        suc_pause+=1
                        logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告成功下架')
                    else:
                        logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告下架失败')
                
                if action_del_pro:

                    # res_get_bb=await self.yb_get_time_graph(page,[aditem])
                    # logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告,删除前下载小时报表{res_get_bb}')
                    # if res_get_bb['code']==0:
                        res_del_pro=await plw_xp_del_pro(page,basic_info,[int(cur_itemid)])
                        if res_del_pro and res_del_pro['code']==0 and res_del_pro['data']['result'][0]['code']==0:
                            is_del_pro=1
                            suc_del+=1
                            logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},成功删除产品')
                        else:
                            logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},删除产品失败')

                if is_jl:
                    pdata={
                        'bid':bid,
                        'shopid':self.shopid,
                        'bname':bname,
                        'country':basic_info['Country'],
                        'sjbm':self.sjbm,
                        'yybm':self.yybm,
                        'campaign_id':str(cur_campid),
                        'itemid':cur_itemid,
                        'random_code':cur_random_code,
                        'title':cur_pname,
                        'cost':cost,
                        'add_to_cart_buyers':add_to_cart_buyers,
                        'uv_to_add_to_cart_rate':uv_to_add_to_cart_rate,
                        'impression':impression,
                        'CTR':ctr,
                        'action_txt':action_txt,
                        'is_pause_ad':is_pause_ad,
                        'is_del_pro':action_del_pro,
                        'click':click
                    }

                    zds=list(pdata.keys())
                    paras=list(pdata.values())

                    aff_jl=self.ms.merge_into('ShopeeAdsPaesed',zds,paras,['campaign_id'],True)
                    logging.info(f'店铺:《{bname}》,{bid},广告:{cur_campid},itemid:{cur_itemid},记录操作:{aff_jl}')

            if itemid_atc_db:
                i_www_str=','.join([f"'{ccc_itemid}'" for ccc_itemid in itemid_atc_db])
                ad_status='加购达标'
                sql_jg=f'''update ShopeeAdsMove set is_paused=1,is_del=0,ads_status='{ad_status}'
                            where itemid_new in ({i_www_str})
                        '''
                aff_jgdb=self.ms.ExecNoQuery(sql_jg)
                logging.info(f'店铺:《{bname}》,{bid},表:《ShopeeAdsMove》,更新{ad_status}:{aff_jgdb}')
            
            if itemid_atc_bdb:
                i_www_str=','.join([f"'{ccc_itemid}'" for ccc_itemid in itemid_atc_bdb])
                ad_status='加购不达标'
                sql_jg=f'''update ShopeeAdsMove set is_paused=1,is_del=1,ads_status='{ad_status}'
                            where itemid_new in ({i_www_str})
                        '''
                aff_jgdb=self.ms.ExecNoQuery(sql_jg)
                logging.info(f'店铺:《{bname}》,{bid},表:《ShopeeAdsMove》,更新{ad_status}:{aff_jgdb}')
            
            if itemid_atc_rate:
                i_www_str=','.join([f"'{ccc_itemid}'" for ccc_itemid in itemid_atc_rate])
                ad_status='ATC Rate不达标'
                sql_jg=f'''update ShopeeAdsMove set is_paused=1,is_del=1,ads_status='{ad_status}'
                            where itemid_new in ({i_www_str})
                        '''
                aff_jgdb=self.ms.ExecNoQuery(sql_jg)
                logging.info(f'店铺:《{bname}》,{bid},表:《ShopeeAdsMove》,更新{ad_status}:{aff_jgdb}')
            
            if itemid_ctr:
                i_www_str=','.join([f"'{ccc_itemid}'" for ccc_itemid in itemid_ctr])
                ad_status='CTR不达标'
                sql_jg=f'''update ShopeeAdsMove set is_paused=1,is_del=1,ads_status='{ad_status}'
                            where itemid_new in ({i_www_str})
                        '''
                aff_jgdb=self.ms.ExecNoQuery(sql_jg)
                logging.info(f'店铺:《{bname}》,{bid},表:《ShopeeAdsMove》,更新{ad_status}:{aff_jgdb}')


            logging.info(f'店铺:《{bname}》,{bid},需暂停:{need_paused_count},成功暂停:{suc_pause},需删除:{need_delpro_count},成功删除:{suc_del}')
            return_res={'code':0,'msg':'执行成功','aff':suc_pause}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':-3,'msg':str(e)}

            
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_move_ads(self):

        '''广告测品转平台'''
        bid=self.bid
        bname=self.dpName
        dpName=bname
        basic_info=self.basic_info
        host=self.host
        country=basic_info['Country']

        lg_map={
            '印尼':'印尼语',
            '马来西亚':'英语',
            '泰国':'泰语',
            '新加坡':'英语',
            '越南':'越南语'
        }
        cur_lg=lg_map[country]
        try:

            res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
            if not res_bbb:
                return {'code':-1,'msg':'启动浏览器失败'}
            plw,browser=res_bbb
        
            defaultContext = browser.contexts[0]
            page =await defaultContext.new_page()
            url=f'https://{host}/portal/product-mass/import/upload'
            if self.iskj==1:
                url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})


            await plw_repeat_goto(page,url)
            sss=await plw_check_login(page,basic_info)
            if not sss:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-2,'msg':'账户登录失败'}
            await asyncio.sleep(5)

            can_count=await plw_get_can_publish(page,basic_info)
            if can_count==0:
                logging.info(f'店铺:《{bname}》,{bid},可发布数量为0,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':0,'msg':'可发布数量为0','aff':0}
            rs_allcodes=self.ms.ExecQuery('select random_code from ShopeeAdsMove where to_country=?',(country,))
            all_rcodes=[r[0] for r in rs_allcodes]
            list_info=await plw_xp_get_list_count(page,basic_info)
            draft_count=list_info['draft']
            if draft_count<10 and self.rocde_list:
                rcodes=self.rocde_list
                dcmr=await plw_get_ads_excel_pro(page,basic_info,rcodes)
                if dcmr is None:
                    logging.info(f'店铺:《{bname}》,{bid},生成产品批量表错误,退出')
                    await page.close()
                    await plw.stop()
                    close_SunBrowser(bid,self.task_id)
                    return {'code':-3,'msg':'生成产品批量表错误'}
                
                if dcmr!=0:

                    file_names=os.listdir(dcmr)
                    for j,file_name in enumerate(file_names,start=1):

                        file_path=os.path.join(dcmr,file_name)
                        logging.info(f'店铺:《{self.dpName}》,{self.bid},开始上传第 {j} 个文件:《{file_path}》')
                        upload_ipt=await plw_wait_xpath(page,'//input[@class="eds-file-uploader uploader eds-upload__input"]')
                        await upload_ipt.set_input_files(file_path)
                        await asyncio.sleep(5)

                    res_reports=await plw_xp_get_report(page,file_names,self.basic_info)
                    for fff_nnn,res_report in res_reports.items():
                        logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传结束')
                        rp_state='Successful'
                        rp_status=res_report['record_status']
                        suc_count=res_report['success_count']
                        handled_count=res_report['handled_count']
                        if suc_count==0:
                            rp_state='Unsuccessful'
                        if rp_status==7 or handled_count==0:
                            rp_state='Failed'
                        
                        if rp_state!='Successful':
                            logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传失败')
                        else:
                            logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传成功')
                            await asyncio.sleep(1)



            await asyncio.sleep(3)
            draft_list=await plw_xp_get_draftlist(page,basic_info)

            suc_draft_rcodes=[]
            suc_draft_map={}
            
            for draft_pitem in draft_list:
                d_itemid=str(draft_pitem['id'])
                ptit=draft_pitem['name']
                rcode_mat= re.search(r'.*\|(.{8})\|$',ptit)
                rcode=rcode_mat.group(1) if rcode_mat else None
                if rcode:
                    suc_draft_map[rcode]=d_itemid
                    suc_draft_rcodes.append(rcode)
            
            if suc_draft_rcodes:
                wstr_suc_rcode=','.join([f"'{rcode}'" for rcode in suc_draft_rcodes])
                aff_draft=self.ms.ExecNoQuery(f"update ShopeeAdsMove set is_fy=1,is_draft=1 where to_country='{country}' and random_code in ({wstr_suc_rcode})")
                logging.info(f'店铺:《{bname}》,{bid},草稿箱共 {len(draft_list)} 个产品,其中标记测品:{aff_draft} 个')
            
            rs_qqc=self.ms.ExecQuery('select word_blacklist from Blacklist where word_language=?',(cur_lg,))
            qqc_list=[r[0] for r in rs_qqc]
            logging.info(f'店铺:《{bname}》,{bid},第三步,从草稿箱上架 {len(draft_list[:can_count])} 个 产品,加载 {len(rs_qqc)} 个{cur_lg}侵权词')
            
            for dj,pro_draft_list in enumerate(draft_list[:can_count],start=1):
                ptit=pro_draft_list['name']
                d_itemid=pro_draft_list['id']
                d_pid=pro_draft_list['parent_sku']
                rcode_mat= re.search(r'.*\|(.{8})\|$',ptit)
                rcode=rcode_mat.group(1) if rcode_mat else None
                if not is_valid_name(ptit,qqc_list):
                    res_del=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    aff_reset=0
                    aff_reset2=0
                    if res_del:
                        if res_del['code']==0:
                            del_list=res_del['data']['result']
                            if del_list:
                                aff_reset=self.ms.ExecNoQuery('update s1688pro set is_wg=1 where itemid=?',(str(d_pid),))
                                aff_reset2=self.ms.ExecNoQuery('update ShopeeAdsMove set is_publish=-2 where to_country=? and random_code=?',(country,rcode))

                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,标题包含侵权词跳过,标记删除:{aff_reset}-{aff_reset2}')
                    continue

                quality_violation_result=pro_draft_list['quality_violation_result']
                if quality_violation_result>0:
                    res_del=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    aff_reset=0
                    aff_reset2=0
                    if res_del:
                        if res_del['code']==0:
                            del_list=res_del['data']['result']
                            if del_list:
                                aff_reset=self.ms.ExecNoQuery('update s1688pro set is_wg=1 where itemid=?',(str(d_pid),))
                                aff_reset2=self.ms.ExecNoQuery('update ShopeeAdsMove set is_publish=-1 where to_country=? and random_code=?',(country,rcode))

                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,违规跳过,标记删除:{aff_reset}-{aff_reset2}')
                    continue

                if rcode not in all_rcodes:

                    res_del=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,非测品数据跳过,标记删除：{res_del}')
                    continue


                edit_url=f'https://{host}/portal/product/unpublished/{d_itemid}'
                await plw_repeat_goto(page,edit_url)
                sss=await plw_check_login(page,basic_info)
                if not sss:
                    await page.close()
                    await plw.stop()
                    close_SunBrowser(bid,self.task_id)
                    return {'code':-2,'msg':'账户登录失败'}
                
                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,开始发布...')
                await asyncio.sleep(3)
                el_tc=page.locator('//div[text()="Discard changes?"]/..//span[text()="Cancel"]')
                if (await el_tc.count()>0):
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,出现取消弹窗点击')
                    await el_tc.click(delay=200)
                    await asyncio.sleep(3)

                is_tc=False
                wait_lm=0
                while True:
                    try:
                        el_select_category= page.locator('xpath=//div[@class="category-select-item"]')
                        if (await el_select_category.count())>0:
                            ebtn= el_select_category.nth(0).locator('xpath=./div[@class="category-select-radio"]/div[1]')
                            await ebtn.click(delay=200)
                        await asyncio.sleep(3)

                        el_clm=page.locator('xpath=//div[@class="product-category-text"]/span[1]')
                        lmtxt=await el_clm.text_content()
                        if lmtxt !='Please set category':
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,成功选中类目')
                            break
                    except Exception as e:
                        traceback.print_exc()
                        await asyncio.sleep(2)
                    wait_lm+=1
                    if wait_lm>7:
                        is_tc=True
                        break
                if is_tc:
                    res_del=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    aff_reset2=0
                    if res_del:
                        if res_del['code']==0:
                            del_list=res_del['data']['result']
                            if del_list:
                                aff_reset2=self.ms.ExecNoQuery('update ShopeeAdsMove set is_publish=-3 where to_country=? and random_code=?',(country,rcode))
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,无法选择类目跳过,标记删除:{aff_reset2}')
                    continue

                await asyncio.sleep(5)

                el_ipt_des=page.locator('xpath=//div[@componentkey="ProductDescriptionEditor"]//textarea[1]')
                if (await el_ipt_des.count())>0:

                    des_txt=await el_ipt_des.input_value()
                    is_chinese,replace_txt=remove_chinese(des_txt)
                    if is_chinese==1:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,描述出现中文,需替换')
                        await el_ipt_des.fill(replace_txt)
                        await asyncio.sleep(1)


                is_direct=True
                upload_img=page.locator('xpath=//span[@class="eds-radio__label" and text()="Image"]')

                if (await upload_img.count())>0:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品,需补充尺码图')
                    is_direct=False
                    rs_1688=self.ms.ExecQuery(f'select image from s1688pro where itemid=?',(d_pid,))
                    if len(rs_1688)==0:
                        res_del=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                        aff_reset2=0
                        if res_del:
                            if res_del['code']==0:
                                del_list=res_del['data']['result']
                                if del_list:
                                    aff_reset2=self.ms.ExecNoQuery('update ShopeeAdsMove set is_publish=-4 where to_country=? and random_code=?',(country,rcode))
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,无法补充尺码图,标记删除:{aff_reset2}')
                        continue
                    size_img_url=rs_1688[0][0]

                    load_fail=False
                    for _ in range(5):
                        try:
                            #img_url=size_img_url
                            img_url=f"http://155.94.192.2/cg/cjt/ImageProxy.aspx?url={size_img_url}"
                            res_img=requests.get(img_url,timeout=60)
                            if res_img.status_code==200:
                                imgcot=res_img.content
                                load_fail=True
                                break
                        except Exception as e:
                            print(e)
                        await asyncio.sleep(3)
                    
                    if not load_fail:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,图片加载失败跳过')
                        continue
                        
                        
                    os.makedirs(f'临时尺码图',exist_ok=True)
                    characters = string.ascii_letters + string.digits
                    random_code = ''.join(random.choice(characters) for _ in range(4))
                    img_path=f'临时尺码图/{random_code}_{getTimeStr()}.jpg'
                    with open(img_path,'wb') as f:
                        f.write(imgcot)

                    el_select_img=page.locator('xpath=//span[@class="eds-radio__label" and text()="Image"]')
                    try:
                        await el_select_img.click(delay=200)
                    except Exception as e:
                        print(e)
                        continue
                    await asyncio.sleep(3)

                    upload_img=await plw_wait_xpath(page,'//div[@class="product-image-size-chart"]//input[@class="eds-upload__input"]')
                    await upload_img.set_input_files(img_path)
                    while True:
                        el_img_ck=page.locator('xpath=//div[@class="image-size-chart"]//div[@class="shopee-file-upload pic"]/div[1]')

                        try:
                            cstyle=await el_img_ck.get_attribute('style')
                        except Exception as e:
                            print(e)
                            break

                        if cstyle and 'background-image: url' in cstyle:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品,成功上传尺码图')
                            os.remove(img_path)
                            break
                        await asyncio.sleep(3)

                el_attribute_select_list=page.locator('xpath=//div[@class="mandatory"]/ancestor::div[@class="attribute-select-item"]')
                select_item_count=await el_attribute_select_list.count()
                if select_item_count==1:
                    await asyncio.sleep(3)
                    select_item_count=await el_attribute_select_list.count()
                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},共 {select_item_count} 项必填项,开始填写...')
                is_wait_opt_timeout=False #判断是否填写必填项超时
                for sj in range(select_item_count):
                    
                    el_row_tit=el_attribute_select_list.nth(sj).locator('xpath=.//div[@class="item-title"]/div[1]')
                    try:
                        speti_name=await el_row_tit.text_content(timeout=5000)
                    except Exception as e:
                        break
                    if 'Brand' in speti_name and 'Applicable Mobile' not in speti_name:
                        continue
                    is_direct=False
                    el_ipt=el_attribute_select_list.nth(sj).locator('xpath=.//input[1]')
                    bt_ipt_count=await el_ipt.count()
                    if bt_ipt_count>0:
                        for iptjjj in range(bt_ipt_count):
                            await el_ipt.nth(iptjjj).fill('220')
                            await asyncio.sleep(1)
                        continue

                    if 'Expiry Date' in speti_name:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性是日期属性特殊处理...')
                        is_wait_opt_timeout=True
                        break

                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》,开始填写')
                    el_xl=el_attribute_select_list.nth(sj).locator('xpath=./div[1]/div[2]//div[@class="eds-select"]')
                    #需填写有效期的操作
                    el_xl_btn=el_attribute_select_list.nth(sj).locator('xpath=./div[1]/div[2]//div[@class="eds-selector__suffix"]')
                    el_xl_ipt=el_xl.locator('xpath=.//div[contains(@class,"placeholder")]')
                    if (await el_xl_ipt.count())==0:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》已经预填写跳过...')
                        continue
                
                    is_mut=False
                    wait_opt=0
   
                    while True:
                        try:
                            await el_xl_btn.click(delay=200)
                        except Exception as e:
                            print(e)
                        el_opts=page.locator('xpath=//ul[@class="eds-dropdown-menu"]//div[@class="eds-option"]')
                        el_opts2=page.locator('xpath=//ul[@class="eds-dropdown-menu"]//div[@class="eds-option multiple"]')
                        if (await el_opts.count())>0:
                            break
                        if (await el_opts2.count())>0:
                            el_opts=el_opts2
                            is_mut=True
                            break
        
                        await asyncio.sleep(3)
                        wait_opt+=1
                        if wait_opt>10:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》填写超时退出')
                            is_wait_opt_timeout=True
                            break
                    
                    if is_wait_opt_timeout:
                        break
                    
                    is_select=False
                    for opj in range(await el_opts.count()):
                        el_copt=el_opts.nth(opj)
                        try:
                            el_txt=(await el_copt.text_content(timeout=10000)).lower()
                        except Exception as e:
                            print(e)
                            break
                        if el_txt.startswith('no') or el_txt.startswith('oth') or '14 years' in el_txt:
                            try:
                                await el_copt.click(delay=200)
                                is_select=True
                                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性,选中:<{el_txt}>,退出')
                                break
                            except Exception as e:
                                print(e)
                                
                    if not is_select:
                        try:
                            await el_opts.nth(0).click(delay=200)
                        except Exception as e:
                            print(e)
                    
                    if is_mut:

                        try:
                            await el_xl_btn.click(delay=200)
                        except Exception as e:
                            print(e)

                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},必填项,填写完毕')
                await asyncio.sleep(1)
                if country=='马来西亚':
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},填写包裹体积...')
                    el_parcel=page.locator('xpath=//div[@data-auto-correct-key="dimension"]/div[@class="edit-row-right-full"]')
                    if (await el_parcel.count())>0:
                        el_width_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.width"]//input')
                        await el_width_ipt.fill('15')
                        await asyncio.sleep(1)
                        el_length_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.length"]//input')
                        await el_length_ipt.fill('20')
                        await asyncio.sleep(1)
                        el_high_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.height"]//input')
                        await el_high_ipt.fill('10')
                        await asyncio.sleep(1)
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},包裹体积填写完毕')
                        await asyncio.sleep(3)

                await asyncio.sleep(2)
                el_shipping=page.locator('xpath=//div[@class="product-shipping container"]//div[@class="grid optional-item"]//div[@class="eds-switch eds-switch--close eds-switch--normal"]')
                shipping_count=await el_shipping.count()
                if shipping_count>0 and country in ['马来西亚','泰国','越南'] :

                    el_first_shipping=el_shipping.nth(0)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},选择运费')
                    try:
                        await el_first_shipping.click(delay=200)
                        await asyncio.sleep(2)
                    except Exception as e:
                        print(e)
                    el_qr_btn=page.locator('xpath=//div[contains(., "Once this channel is enabled")]//button[1]')
                    if (await el_qr_btn.count())>0:
                        try:
                            await el_qr_btn.click(delay=200)
                            await asyncio.sleep(2)
                        except Exception as e:
                            print(e)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},成功选中第一个运费')
                await asyncio.sleep(3)

                if is_wait_opt_timeout:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},等待超时')
                    continue
                el_publist=page.locator('xpath=//span[text()="Publish"]')
                try:
                    await el_publist.click(delay=200)
                except Exception as e:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},点击publish错误')

                wait_publish=0
                tzq=0
                while True:
                    try:
                        cot=await page.content()
                        if ('Product has been successfully published' in cot) or ('Listed successfully!' in cot) or '/portal/product/list/unpublished/draft' in page.url :
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},成功发布,剩余:{len(draft_list)-dj} 个产品')
                            break
                        if 'Cannot create product because the shop is under penalty' in cot:
                            await page.close()
                            await plw.stop()
                            close_SunBrowser(bid,self.task_id)
                            return {'code':0,'msg':'店铺受到惩罚','aff':0}
                    
                        el_save_publish=page.locator('//div[text()="Are you sure to Save and Publish ?"]/../../..//span[text()="Save and Publish"]')

                        if (await el_save_publish.count())>0:
                            try:
                                await el_save_publish.click(delay=200)
                                await asyncio.sleep(1)
                            except Exception as e:
                                print(e)
                        

                        await asyncio.sleep(1)
                        wait_publish+=1
                        tzq+=1
                        if wait_publish>21:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},发布超时失败,剩余:{len(draft_list)-dj} 个产品')
                            break

                        if tzq==20:
                            el_publist=page.locator('xpath=//span[text()="Publish"]')
                            try:
                                await el_publist.click(delay=200)
                            except Exception as e:
                                print(e)

                            tzq=0
                    except Exception as e:
                        traceback.print_exc()
                    await asyncio.sleep(1)
                await asyncio.sleep(3)

            has_publish_map={}
            pro_list=await plw_xp_get_prolist(page,basic_info)
            aff_has_publish=0
            if pro_list:
                for pro in pro_list:
                    p_itemid=str(pro['id'])
                    p_name=pro['name']
                    rcode_mat= re.search(r'.*\|(.{8})\|$',p_name)
                    cc_rcode=rcode_mat.group(1) if rcode_mat else None
                    if cc_rcode in all_rcodes:
                        has_publish_map[cc_rcode]=p_itemid
                        sql_ppp=f'''update ShopeeAdsMove set 
                                        itemid_new='{p_itemid}',
                                        is_fy=1,
                                        is_draft=1,
                                        is_publish=1
                                        where to_country='{country}'
                                        and random_code='{cc_rcode}'
                                        '''
                        aff_has_publish+=self.ms.ExecNoQuery(sql_ppp)
            
            logging.info(f'店铺:《{bname}》,{bid},成功上架 {len(has_publish_map.keys())} 个产品,标记上架:{aff_has_publish}')

            aff_has_ad=0
            ad_list=await plw_xp_get_adbb(page,basic_info)
            if ad_list:
                for ad_item in ad_list:
                    a_itemid=str(ad_item['manual_product_ads']['item_id'])
                    campaign_id=str(ad_item['campaign']['campaign_id'])
                    a_name=ad_item['title']
                    rcode_mat= re.search(r'.*\|(.{8})\|$',a_name)
                    cc_rcode=rcode_mat.group(1) if rcode_mat else None
                    if cc_rcode in all_rcodes:
                       
                        sql_ppp=f'''update ShopeeAdsMove set 
                                        itemid_new='{a_itemid}',
                                        is_fy=1,
                                        is_draft=1,
                                        is_publish=1,
                                        is_create_ad=1,
                                        campaign_id='{campaign_id}',
                                        to_bid='{bid}',
                                        to_bname=?,
                                        to_yybm='{self.yybm}',
                                        pname=?
                                        where to_country='{country}'
                                        and random_code='{cc_rcode}'
                                        '''
                        aff_has_ad+=self.ms.ExecNoQuery(sql_ppp,(bname,a_name))
            
                logging.info(f'店铺:《{bname}》,{bid},第四步,共获取 {len(ad_list)} 个广告,标记 {aff_has_ad} 个')

            sql_str3=f"select itemid_new from ShopeeAdsMove where to_country='{country}' and is_publish=1 and is_create_ad=0"
            rs3=self.ms.ExecQuery(sql_str3)
            if len(rs3)==0:
                logging.info(f'店铺:《{bname}》,{bid},当前没有需要发布的广告')
            else:
                pass

            return_res={'code':0,'msg':'执行成功','aff':0}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':-3,'msg':str(e)}

            
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_delete_product(self):

        '''删除全店产品'''
        bid=self.bid
        dpName=self.dpName
        basic_info=self.basic_info
        host=self.host
        country=self.basic_info['Country']
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/product/list/live/all?operationSortBy=recommend_v2'
        if self.iskj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})

        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        await asyncio.sleep(5)
        if country=='泰国':
            zd_dc_bid='th_dc_bid'
            zd_dc_shopid='th_dc_shopid'
            zd_is_dc='is_th_big_dc'
            zd_dctime='thdaochuTime'
            zd_del_count='th_del_count'

        else:
            zd_dc_bid='distribution_export_bid'
            zd_dc_shopid='distribution_export_shopid'
            zd_is_dc='is_distribution_export'
            zd_dctime='daochuTime'
            zd_del_count='del_count'

        try:
            logging.info(f'店铺:《{dpName}》,{bid},第一步,获取所有上架产品...')
            pro_list=await plw_xp_get_prolist(page,basic_info,'all')
            logging.info(f'店铺:《{dpName}》,{bid},共获取到 {len(pro_list)} 个上架产品,开始删除...')
            if pro_list is None:
                logging.info(f'店铺:《{dpName}》,{bid},获取产品列表错误,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-3,'msg':'获取产品列表错误'}
            itemids_need_del=[]
            itemid_rcode_map={}
            for pro in pro_list:
                p_itemid=str(pro['id'])
                p_name=pro['name']
                rcode_mat= re.search(r'.*\|(.{8})\|$',p_name)
                rcode=rcode_mat.group(1) if rcode_mat else None
                itemid_rcode_map[p_itemid]=rcode
                itemids_need_del.append(pro['id'])
 
        
            for j in range(math.ceil(len(itemids_need_del)/48)):
                cur_itemid_list=itemids_need_del[j*48:(j+1)*48]
                res_del=await plw_xp_del_pro(page,basic_info,cur_itemid_list)
                cur_sjm_list=[]
                cur_has_del=[]
                aff_reset=0
                if res_del:
                    if res_del['code']==0:
                        del_list=res_del['data']['result']
                        for del_data in del_list:
                            if del_data['code']==0:
                                cur_has_del.append(str(del_data['id']))
                                if itemid_rcode_map.get(str(del_data['id'])):
                                    cur_sjm_list.append(itemid_rcode_map.get(str(del_data['id'])))
                        
                        if cur_sjm_list:
                            wstr=','.join([f"'{sjm}'" for sjm in cur_sjm_list])
                            sql_del=f'''update s1688pro set
                                        {zd_dc_bid}=null,
                                        {zd_dc_shopid}=null,
                                        {zd_is_dc}=0
                                        where random_code in ({wstr})
                                '''
                            aff_reset+=self.ms.ExecNoQuery(sql_del)
                        logging.info(f'店铺:《{dpName}》,{bid},第 {j+1} 页,成功删除:{len(del_list)} 个上架产品,有随机码 {len(cur_sjm_list)}个,成功标记:{aff_reset}') 

            logging.info(f'店铺:《{dpName}》,{bid},第二步,获取所有草稿箱产品...')
            draft_list=await plw_xp_get_draftlist(page,basic_info)
            logging.info(f'店铺:《{dpName}》,{bid},共获取到 {len(draft_list)} 个草稿箱产品,开始删除...')
            itemid_parent_map={str(dpro['id']):str(dpro['parent_sku']) for dpro in draft_list}

            for j in range(math.ceil(len(draft_list)/100)):
                cur_draft_list=draft_list[j*100:(j+1)*100]
                cur_itemids=[cdpro['id'] for cdpro in cur_draft_list]
                res_del=await plw_xp_del_draftpro(page,basic_info,cur_itemids)
                cur_has_del=[]
                cur_parent_list=[]
                aff_reset2=0
                if res_del:
                    if res_del['code']==0:
                        del_list=res_del['data']['result']
                        for del_data in del_list:
                            if del_data['code']==0:
                                cur_has_del.append(str(del_data['unpublished_id']))
                                if itemid_parent_map.get(str(del_data['unpublished_id'])):
                                    cur_parent_list.append(itemid_parent_map.get(str(del_data['unpublished_id'])))
                        
                        if cur_parent_list:
                            wstr=','.join([f"'{sjm}'" for sjm in cur_parent_list])
                            aff_reset2+=self.ms.ExecNoQuery(f'update s1688pro set {zd_dc_bid}=null,{zd_dc_shopid}=null,{zd_is_dc}=0 where itemid in ({wstr})')
                        logging.info(f'店铺:《{dpName}》,{bid},第 {j+1} 页,成功删除:{len(del_list)} 个草稿箱产品,可标记 {len(cur_parent_list)}个,成功标记:{aff_reset2}')   
            return_res={'code':0,'msg':'执行成功','aff':1}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':0,'msg':str(e)}

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_get_time_graph(self,page,pro_real_bb_list):

        '''获取区间广告报表'''
        bid=self.bid
        dpName=self.dpName
        basic_info=self.basic_info
        host=self.host
        sjbm=self.sjbm
        yybm=self.yybm
        country=basic_info['Country']
        dqsq=7
        if country in ['马来西亚','新加坡']:
            dqsq=8
    
        # res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        # if not res_bbb:
        #     return {'code':-1,'msg':'启动浏览器失败'}
        # plw,browser=res_bbb    
        # defaultContext = browser.contexts[0]
        # page =await defaultContext.new_page()


    
        try:
            shopid=await plw_xp_get_shopid(page,basic_info)
            suc=0
            logging.info(f'店铺:《{dpName}》,{bid},开始采集昨日24小时广告报表数据...')
            
            st_time_sq8,ed_time_sq9=get_shopee_timestamp('yesterday',8)
            for aj,pro_bb in enumerate(pro_real_bb_list,start=1):
                manual_product_ads=pro_bb['manual_product_ads']
                campaign=pro_bb['campaign']
                cur_itemid=str(manual_product_ads['item_id'])
                cur_campaign_id=str(campaign['campaign_id'])
                cur_pname=pro_bb['title']
                cur_random_code=None
                mat=re.search(r'.*\|(.{8})\|$',cur_pname)
                if mat:
                    cur_random_code=mat.group(1)
                ad_start_time=timestamp_to_datetime(campaign['start_time'])
                cur_img=pro_bb['image']
                cur_img=f'{IMG_HOST_MAP[country]}{cur_img}'
                
                if aj==1:
                    zw=await plw_xp_get_zw(page,basic_info,cur_campaign_id)
                    basic_info['device_sz_fingerprint']=zw
                
                logging.info(f'店铺:《{dpName}》,{bid},开始请求第 {aj} 个广告《{cur_campaign_id}》的区间报表...')
                res_bb_list=await plw_xp_get_adbb_with_time(page,basic_info,cur_campaign_id)
                if res_bb_list:
                    aff_time_bb=0
                    for time_bb in res_bb_list:
                        cur_timestamp=int(time_bb['key'])
                        cur_date=timestamp_to_date(cur_timestamp,dqsq)
                        data_date=cur_date.strftime('%Y-%m-%d')
                        cur_time_slot=cur_date.hour
                        rpt=time_bb['metrics']
                        pbasic={
                            "bid": bid,
                            "shopid": shopid,
                            "purl":f'https://{host.replace("seller.","")}/{shopid}/{cur_itemid}/',
                            "ad_url":f"https://{host}/portal/marketing/pas/product/manual/{campaign['campaign_id']}",
                            "bname": dpName,
                            "country":country,
                            "sjbm": sjbm,
                            "yybm": yybm,
                            "data_date": data_date,
                            "time_slot":cur_time_slot,
                            "dtype": 'today',
                            "campaign_id": cur_campaign_id,
                            "itemid": cur_itemid,
                            "random_code": cur_random_code,
                            "daily_budget": campaign['daily_budget']/100000,
                            "total_budget": campaign['total_budget']/100000,
                            "roi_two_target": campaign['roi_two_target']/100000,
                            "start_time": ad_start_time,
                            "state": pro_bb['state'],
                            "subtype": pro_bb['subtype'],
                            "type": pro_bb['type'],
                            "title": cur_pname,
                            "image": cur_img,
                            "bidding_strategy": manual_product_ads['bidding_strategy'],
                            "cps": manual_product_ads['cps'],
                            "product_placement": manual_product_ads['product_placement'],
                            "impression": rpt['impression'],
                            "click": rpt['click'],
                            "ctr": rpt['ctr'],
                            "cpc": rpt['cpc']/100000,
                            "cost": rpt['cost']/100000,
                            "checkout": rpt['checkout'],
                            "checkout_rate": rpt['checkout_rate'],
                            "order_count": rpt['broad_order'],
                            "order_amount": rpt['broad_order_amount'],
                            "gmv": rpt['broad_gmv']/100000,
                            "roi": rpt['broad_roi'],
                            "avg_rank": rpt['avg_rank'],
                            "page_views": rpt['page_views'],
                            "unique_visitors": rpt['unique_visitors'],
                            "reach": rpt['reach'],
                            "product_click": rpt['product_click'],
                            "product_impression": rpt['product_impression'],
                            "product_ctr": rpt['product_ctr']
                        }
                        zds=list(pbasic.keys())
                        paras=list(pbasic.values())
                        zd_on=['itemid','data_date','time_slot','state']
                        aff_time_bb+=tms.merge_into('ShopeeAdsReport',zds,paras,zd_on,True)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {aj} 个广告《{cur_campaign_id}》,区间数据请求:{len(res_bb_list)},保存:{aff_time_bb}')
                    suc+=aff_time_bb
                else:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {aj} 个广告《{cur_campaign_id}》,请求失败')

            return_res={'code':0,'msg':'执行成功','aff':suc}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':-3,'msg':'执行出错'}
        return return_res

    async def yb_get_time_llgraph(self):

        '''获取区间流量报表'''
        bid=self.bid
        bname=self.dpName
        basic_info=self.basic_info
        host=self.host
        country=self.basic_info['Country']
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()
        t0=asyncio.create_task(plw_check_pass(page,basic_info))
        url=f'https://{host}/datacenter/product/performance'
        if self.iskj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})

        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        suc=0
        try:
            await plw_wait_xpath(page,'//div[@class="cell" and (text()="Product Information" or text()= "商品")]')
            suc=0

            logging.info(f'店铺:《{bname}》,{bid},当开始采集昨日报表数据..')
            pro_real_bb_list=await plw_xp_get_pro_performance(page,basic_info,'y')
            suc+=upload_performance(basic_info,pro_real_bb_list,'y')
            
            logging.info(f'店铺:《{bname}》,{bid},当开始采集七天报表数据..')
            pro_real_bb_list=await plw_xp_get_pro_performance(page,basic_info,'w')
            suc+=upload_performance(basic_info,pro_real_bb_list,'w')

            # logging.info(f'店铺:《{bname}》,{bid},开始采集当日报表数据...')
            # col_names=tms.GetCol('ShopeeProPerformance')
            # pro_real_bb_list=await plw_xp_get_pro_performance(page,basic_info,'r')
            # sq=SQ_Map[country]
            # utc_plus_7 = datetime.timezone(datetime.timedelta(hours=sq))
            # now = datetime.datetime.now(utc_plus_7)
            # today=now.date()
            # for pj,pro_bb in enumerate(pro_real_bb_list,start=1):
            #     if pro_bb['display_tag_label']=='psd_label_deleted':
            #         continue
                
            #     cur_itemid=str(pro_bb['id'])
            #     cur_pname=pro_bb['name']
            #     cur_random_code=None
            #     mat=re.search(r'.*\|(.{8})\|$',cur_pname)
            #     if mat:
            #         cur_random_code=mat.group(1)
                
            #     cur_img=pro_bb['image']
            #     cur_img=f'{IMG_HOST_MAP[country]}{cur_img}'
            #     tplist=await plw_xp_get_llbb_with_time(page,basic_info,cur_itemid)
            #     logging.info(f'第 {pj} 个 itemid:{cur_itemid},开始获取当日报表详情,剩余总量:{len(pro_real_bb_list)-pj}')
            #     tbaff=0
            #     for tpitem in tplist:
            #         dt_utc = datetime.datetime.fromtimestamp(tpitem['t'], tz=datetime.timezone.utc)
            #         dt_plus7 = dt_utc.astimezone(datetime.timezone(datetime.timedelta(hours=sq)))
            #         cur_hour = dt_plus7.hour
            #         pbasic={}

            #         for k,v in tpitem.items():
            #             if k in col_names:
            #                 pbasic[k]=v
                    
            #         pbasic['itemid']=cur_itemid
            #         pbasic['image']=cur_img
            #         pbasic['name']=cur_pname
            #         pbasic['random_code']=cur_random_code
            #         pbasic['dtype']='小时'
            #         pbasic['bname']=bname
            #         pbasic['bid']=bid
            #         pbasic['shopid']=self.shopid
            #         pbasic['yybm']=self.yybm
            #         pbasic['country']=country
            #         pbasic['data_date']=today
            #         pbasic['time_slot']=cur_hour
            #         zds=list(pbasic.keys())
            #         paras=list(pbasic.values())
            #         zd_on=['itemid','data_date','time_slot']
            #         tbaff+=tms.merge_into('ShopeeProPerformance',zds,paras,zd_on,True)

            #     logging.info(f'第 {pj} 个 itemid:{cur_itemid},当日报表数据,共保存:{tbaff},剩余总量:{len(pro_real_bb_list)-pj}')

            logging.info(f'店铺:《{bname}》,{bid},当开始采集三十天报表数据..')
            pro_real_bb_list=await plw_xp_get_pro_performance(page,basic_info,'m')
            suc+=upload_performance(basic_info,pro_real_bb_list,'m')
            return_res={'code':0,'msg':'执行成功','aff':suc}

        except Exception as e:
            traceback.print_exc()
            return_res={'code':-2,'msg':'执行出错'}

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_th_copyright(self):

        '''泰国铺货过滤侵权'''
        basic_info=self.basic_info
        host=self.host
        dpName=self.dpName
        bid=self.bid
        country=basic_info['Country']
        rs_kyc=self.ms.ExecQuery('select count(*) from ShopHome where KYC=? and bid=?',('异常',bid))
        if rs_kyc[0][0]==1:
            return {'code':0,'msg':'账户kyc异常','aff':0}
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
        lg_map={
            '印尼':'印尼语',
            '马来西亚':'英语',
            '泰国':'泰语',
            '新加坡':'英语'
        }
        cur_lg=lg_map[country]
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/product/list/live/all?operationSortBy=recommend_v2'  
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        await plw_wait_xpath(page,'//div[@class="list-page-header-title"]')

        suc=0
        t0=asyncio.create_task(plw_bring_to_front_if_needed(page))
        cur_time=time.time()
        set_day_range=2

        if country=='泰国':
            zd_dc_bid='th_dc_bid'
            zd_dc_shopid='th_dc_shopid'
            zd_is_dc='is_th_big_dc'
            zd_dctime='thdaochuTime'
            zd_del_count='th_del_count'

        else:
            zd_dc_bid='distribution_export_bid'
            zd_dc_shopid='distribution_export_shopid'
            zd_is_dc='is_distribution_export'
            zd_dctime='daochuTime'
            zd_del_count='del_count'

        try:
            logging.info(f'店铺:《{dpName}》,{bid},第一步,标记并删除数据')
            pro_list=await plw_xp_get_prolist(page,basic_info,'all')
            
            if pro_list is None:
                logging.info(f'店铺:《{dpName}》,{bid},获取产品列表错误,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-4,'msg':'获取产品列表错误'}
            pro_deleted= await plw_xp_get_deletedlist(page,basic_info)
            itemids_need_del=[]
            offerids_right=[]
            offerids_banned=[]
            offerids_deleted=[]
            offerids_reviewing=[]
            offerids_other=[]
            
            for pro in pro_list:
                p_itemid=str(pro['id'])
                p_status=pro['status']
                parent_sku=pro['parent_sku']
                p_create_time=pro['create_time']
                if p_status==1:
                    if (cur_time-p_create_time)>86400*set_day_range:
                        itemids_need_del.append(p_itemid)
                        offerids_right.append(parent_sku)
                elif p_status==3:
                    itemids_need_del.append(p_itemid)
                    offerids_banned.append(parent_sku)
                elif p_status==6:
                    itemids_need_del.append(p_itemid)
                    offerids_reviewing.append(parent_sku)
                else:
                    itemids_need_del.append(p_itemid)
                    offerids_other.append(parent_sku)
            
            for pro1 in pro_deleted:
                parent_sku1=pro1['parent_sku']
                offerids_deleted.append(parent_sku1)

            mark_1688_thright(basic_info,offerids_right,'大数据不侵权','live')
            mark_1688_thright(basic_info,offerids_banned,'大数据侵权','banned')
            mark_1688_thright(basic_info,offerids_deleted,'大数据侵权','deleted')
            mark_1688_thright(basic_info,offerids_reviewing,'大数据侵权','reviewing')
            mark_1688_thright(basic_info,offerids_other,'大数据侵权','other')
            await plw_xp_del_pros(page,basic_info,itemids_need_del)


            can_count=await plw_get_can_publish(page,basic_info,st=2)
            
            logging.info(f'店铺:《{dpName}》,{bid},第二步,补充 {can_count} 个产品到草稿箱')
            if can_count==0:
                logging.info(f'店铺:《{dpName}》,{bid},可发布数量为0,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':0,'msg':'可发布数量为0','aff':0}
            list_info=await plw_xp_get_list_count(page,basic_info)
            draft_count=list_info['draft']
            need_publish_count=can_count if can_count<100 else 100
            if need_publish_count >0 and draft_count<100:

                logging.info(f'店铺:《{dpName}》,{bid},需上架 {need_publish_count} 个产品')

                dcmr=await plw_get_excel_thpro(page,basic_info,need_publish_count)
                if  dcmr is None:
                    logging.info(f'店铺:《{dpName}》,{bid},生成产品批量表错误,退出')
                    await page.close()
                    await plw.stop()
                    close_SunBrowser(bid,self.task_id)
                    return {'code':-6,'msg':'生成产品批量表错误'}
                
                if dcmr!=0:
                    purl=f'https://{host}/portal/product-mass/import/upload'
                    await plw_repeat_goto(page,purl)
                    sss=await plw_check_login(page,basic_info)
                    if not sss:
                        await page.close()
                        await plw.stop()
                        close_SunBrowser(bid,self.task_id)
                        return {'code':-2,'msg':'账户登录失败'}
                    
                    file_names=os.listdir(dcmr)

                    for j,file_name in enumerate(file_names,start=1):

                        file_path=os.path.join(dcmr,file_name)

                        logging.info(f'店铺:《{self.dpName}》,{self.bid},开始上传第 {j} 个文件:《{file_path}》')
                        upload_ipt=await plw_wait_xpath(page,'//input[@class="eds-file-uploader uploader eds-upload__input"]')
                        await upload_ipt.set_input_files(file_path)
                        await asyncio.sleep(5)

                    res_reports=await plw_xp_get_report(page,file_names,self.basic_info)
                    for fff_nnn,res_report in res_reports.items():
                        logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传结束')
                        rp_state='Successful'
                        file_id=res_report['id']
                        rp_status=res_report['record_status']
                        suc_count=res_report['success_count']
                        all_count=res_report['total_count']
                        handled_count=res_report['handled_count']
                        fail_count=all_count-suc_count
                        ctime=timestamp_to_sql_datetime(res_report['ctime'])
                        mtime=res_report['mtime']
                        if mtime!=0:
                            mtime=timestamp_to_sql_datetime(res_report['ctime'])
                        else:
                            mtime=None

                        shopid=res_report['shop_id']
                        
                        if suc_count==0:
                            rp_state='Unsuccessful'
                        if rp_status==7 or handled_count==0:
                            rp_state='Failed'
                        
                        c_file_p=os.path.join(dcmr,fff_nnn)
                        parentids=get_parentid_from_excel(c_file_p)
                        pstr=','.join([f"'{parentid}'" for parentid in parentids])
                        if rp_state!='Successful':
                            aff_reset_pid=self.ms.ExecNoQuery(f"update S1688Pro set {zd_dc_bid}=null where itemid in ({pstr})")
                            logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传失败,重置产品:{aff_reset_pid},')
                        else:
                            now_time=datetime.datetime.now()
                            aff_dc=self.ms.ExecNoQuery(f"update S1688Pro set {zd_is_dc}=1,{zd_dctime}=? where itemid in ({pstr})",(now_time,))
                            logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传成功,标记导出状态:{aff_dc}')
                            await asyncio.sleep(1)
                
            await asyncio.sleep(5)
            rs_qqc=self.ms.ExecQuery('select word_blacklist from Blacklist where word_language=?',(cur_lg,))
            qqc_list=[r[0] for r in rs_qqc]
            logging.info(f'店铺:《{dpName}》,{bid},第三步,草稿箱选择类目并上架,加载 {len(qqc_list)} 个{cur_lg}侵权词')

            await plw_repeat_goto(page,f'https://{host}/portal/product/list/unpublished/draft')
            sss=await plw_check_login(page,basic_info)
            if not sss:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-2,'msg':'账户登录失败'}
            await asyncio.sleep(10)
            # await plw_wait_xpath(page,'//div[@class="draft-product-list-table-row"]') 


            draft_list=await plw_xp_get_draftlist(page,basic_info,target_count=100)
            for dj,pro_draft_list in enumerate(draft_list[:100],start=1):
                ptit=pro_draft_list['name']
                d_itemid=pro_draft_list['id']
                d_pid=pro_draft_list['parent_sku']
                if not is_valid_name(ptit,qqc_list):
                    
                    res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    aff_reset=self.ms.ExecNoQuery('update s1688pro set copyright_th=?,th_live_status=? where itemid=?',('大数据侵权','标题包含侵权词',str(d_pid),))
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,标题包含侵权词跳过,标记删除:{aff_reset}')
                    continue
                quality_violation_result=pro_draft_list['quality_violation_result']
                if quality_violation_result>0:
                    res_del=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    aff_reset=0
                    if res_del:
                        if res_del['code']==0:
                            del_list=res_del['data']['result']
                            if del_list:
                                aff_reset=self.ms.ExecNoQuery('update s1688pro set copyright_th=?,th_live_status=? where itemid=?',('大数据侵权','草稿箱违规',str(d_pid),))
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,违规跳过,标记删除:{aff_reset}')
                    continue

                edit_url=f'https://{host}/portal/product/unpublished/{d_itemid}'
                #edit_url=f'https://seller.shopee.co.id/portal/product/{d_itemid}?pageEntry=product_list'
                await plw_repeat_goto(page,edit_url)
                sss=await plw_check_login(page,basic_info)
                if not sss:
                    await page.close()
                    await plw.stop()
                    close_SunBrowser(bid,self.task_id)
                    return {'code':-2,'msg':'账户登录失败'}
                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,开始发布...')

                await asyncio.sleep(3)
                el_tc=page.locator('//div[text()="Discard changes?"]/..//span[text()="Cancel"]')
                if (await el_tc.count()>0):
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,出现取消弹窗点击')
                    await el_tc.click(delay=200)
                    await asyncio.sleep(3)

                is_tc=False
                wait_lm=0
                while True:
                    el_select_category= page.locator('xpath=//div[@class="category-select-item"]')
                    if (await el_select_category.count())>0:
                        ebtn= el_select_category.nth(0).locator('xpath=./div[@class="category-select-radio"]/div[1]')
                        try:
                            await ebtn.click(delay=200)
                        except Exception as e:
                            print(e)
                    await asyncio.sleep(3)
                    el_clm=page.locator('xpath=//div[@class="product-category-text"]/span[1]')
                    try:
                        lmtxt=await el_clm.text_content()
                        if lmtxt !='Please set category':
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,成功选中类目')
                            break
                    except Exception as e:
                        print(e)
                    wait_lm+=1
                    if wait_lm>10:
                        is_tc=True
                        break
                if is_tc:
                    res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,无法选择类目,删除:{res_del_ccc}')
                    continue

                await asyncio.sleep(5)
                el_ipt_des=page.locator('xpath=//div[@componentkey="ProductDescriptionEditor"]//textarea[1]')
                if (await el_ipt_des.count())>0:
                    des_txt=await el_ipt_des.input_value()
                    is_chinese,replace_txt=remove_chinese(des_txt)
                    if is_chinese==1:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,描述出现中文,需替换')
                        await el_ipt_des.fill(replace_txt)
                        await asyncio.sleep(1)


                is_direct=True
                upload_img=page.locator('xpath=//span[@class="eds-radio__label" and text()="Image"]')
                is_not_size_img=False
                if (await upload_img.count())>0:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品,需补充尺码图')
                    is_direct=False
                    rs_1688=self.ms.ExecQuery(f'select image,images from s1688pro where itemid=?',(d_pid,))
                    if len(rs_1688)==0:
                        res_del=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,无法补充尺码图,标记删除:{res_del}')
                        continue
                    size_img_url=rs_1688[0][0]
                    if (rs_1688[0][1]):
                        imgs=json.loads(rs_1688[0][1])
                    else:
                        imgs=[]
                    sssj=0
                    
                    while True:
                        try:
                            #img_url=size_img_url
                            img_url=f"http://155.94.192.2/cg/cjt/ImageProxy.aspx?url={size_img_url}"
                            res_img=requests.get(img_url,timeout=120)
                            if res_img.status_code==200:
                                imgcot=res_img.content
                                break
                            elif res_img.status_code==500:
                                sssj+=1
                                if sssj<len(imgs):
                                    size_img_url=imgs[sssj]
                                else:
                                    is_not_size_img=True
                                    break
                        except Exception as e:
                            print(e)
                            await asyncio.sleep(3)
                        
                    os.makedirs(f'临时尺码图',exist_ok=True)
                    characters = string.ascii_letters + string.digits
                    random_code = ''.join(random.choice(characters) for _ in range(4))
                    img_path=f'临时尺码图/{random_code}_{getTimeStr()}.jpg'
                    with open(img_path,'wb') as f:
                        f.write(imgcot)

                    el_select_img=page.locator('xpath=//span[@class="eds-radio__label" and text()="Image"]')
                    try:
                        await el_select_img.click(delay=200)
                        await asyncio.sleep(3)
                    except Exception as e:
                        traceback.print_exc()
                        print(e)
                        continue

                    upload_img=await plw_wait_xpath(page,'//div[@class="product-image-size-chart"]//input[@class="eds-upload__input"]')
                    await upload_img.set_input_files(img_path)
                    while True:
                        el_img_ck=page.locator('xpath=//div[@class="image-size-chart"]//div[@class="shopee-file-upload pic"]/div[1]')

                        try:
                            cstyle=await el_img_ck.get_attribute('style')
                        except Exception as e:
                            print(e)
                            break

                        if cstyle and 'background-image: url' in cstyle:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品,成功上传尺码图')
                            os.remove(img_path)
                            break
                        await asyncio.sleep(3)

                if is_not_size_img:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},无法填充尺码图跳过')
                    continue
                el_attribute_select_list=page.locator('xpath=//div[@class="mandatory"]/ancestor::div[@class="attribute-select-item"]')
                select_item_count=await el_attribute_select_list.count()
                if select_item_count==1:
                    await asyncio.sleep(3)
                    select_item_count=await el_attribute_select_list.count()
                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},共 {select_item_count} 项必填项,开始填写...')
                is_wait_opt_timeout=False #判断是否填写必填项超时
                for sj in range(select_item_count):
                    
                    el_row_tit=el_attribute_select_list.nth(sj).locator('xpath=.//div[@class="item-title"]/div[1]')
                    try:
                        speti_name=await el_row_tit.text_content(timeout=5000)
                    except Exception as e:
                        break
                    if 'Brand' in speti_name and 'Applicable Mobile' not in speti_name:
                        continue
                    is_direct=False
                    el_ipt=el_attribute_select_list.nth(sj).locator('xpath=.//input[1]')
                    bt_ipt_count=await el_ipt.count()
                    if bt_ipt_count>0:
                        for iptjjj in range(bt_ipt_count):
                            await el_ipt.nth(iptjjj).fill('220')
                            await asyncio.sleep(1)
                        continue

                    if 'Expiry Date' in speti_name:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性是日期属性特殊处理...')
                        is_wait_opt_timeout=True
                        break

                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》,开始填写')
                    el_xl=el_attribute_select_list.nth(sj).locator('xpath=./div[1]/div[2]//div[@class="eds-select"]')
                    #需填写有效期的操作
                    el_xl_btn=el_attribute_select_list.nth(sj).locator('xpath=./div[1]/div[2]//div[@class="eds-selector__suffix"]')
                    el_xl_ipt=el_xl.locator('xpath=.//div[contains(@class,"placeholder")]')

                    if (await el_xl_ipt.count())==0:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》已经预填写跳过...')
                        continue
                    
                    is_mut=False
                    wait_opt=0
   
                    while True:
                        try:
                            await el_xl_btn.click(delay=200)
                        except Exception as e:
                            print(e)
                        el_opts=page.locator('xpath=//ul[@class="eds-dropdown-menu"]//div[@class="eds-option"]')
                        el_opts2=page.locator('xpath=//ul[@class="eds-dropdown-menu"]//div[@class="eds-option multiple"]')
                        if (await el_opts.count())>0:
                            break
                        if (await el_opts2.count())>0:
                            el_opts=el_opts2
                            is_mut=True
                            break
        
                        await asyncio.sleep(3)
                        wait_opt+=1
                        if wait_opt>10:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》填写超时退出')
                            is_wait_opt_timeout=True
                            break
                    
                    if is_wait_opt_timeout:
                        break
                    
                    is_select=False
                    for opj in range(await el_opts.count()):
                        el_copt=el_opts.nth(opj)
                        try:
                            el_txt=(await el_copt.text_content(timeout=10000)).lower()
                            #print(el_txt)
                        except Exception as e:
                            print(e)
                            break
                            

                        if el_txt.startswith('no') or el_txt.startswith('oth') or '14 years' in el_txt:
                            try:
                                await el_copt.click(delay=200)
                                is_select=True
                                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性,选中:<{el_txt}>,退出')
                                break
                            except Exception as e:
                                print(e)
                                
                    if not is_select:

                        try:
                            await el_opts.nth(0).click(delay=200)
                        except Exception as e:
                            print(e)
                    
                    if is_mut:

                        try:
                            await el_xl_btn.click(delay=200)
                        except Exception as e:
                            print(e)

                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},必填项,填写完毕')
                await asyncio.sleep(3)
                el_shipping=page.locator('xpath=//div[@class="product-shipping container"]//div[@class="grid optional-item"]//div[@class="eds-switch eds-switch--close eds-switch--normal"]')

                shipping_count=await el_shipping.count()

                if shipping_count>0 and country in ['马来西亚','泰国','越南']:

                    el_first_shipping=el_shipping.nth(0)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},选择运费')
                    try:
                        await el_first_shipping.click(delay=200)
                        await asyncio.sleep(2)
                    except Exception as e:
                        print(e)
                    
                    el_qr_btn=page.locator('xpath=//div[contains(., "Once this channel is enabled")]//button[1]')
                    if (await el_qr_btn.count())>0:
                        try:
                            await el_qr_btn.click(delay=200)
                            await asyncio.sleep(2)
                        except Exception as e:
                            print(e)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},成功选中第一个运费')
                await asyncio.sleep(3)

                if is_wait_opt_timeout:
                    res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    aff_reset=self.ms.ExecNoQuery('update s1688pro set copyright_th=?,th_live_status=? where itemid=?',('大数据侵权','等待超时',str(d_pid),))
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,等待超时,标记删除:{aff_reset}')
                    continue
                    
                el_publist=page.locator('xpath=//span[text()="Publish"]')
                try:
                    await el_publist.click(delay=200)
                except Exception as e:
                    res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                    aff_reset=self.ms.ExecNoQuery('update s1688pro set copyright_th=?,th_live_status=? where itemid=?',('大数据侵权','点击publish错误',str(d_pid),))
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},点击publish错误,标记删除:{aff_reset} ')
                    continue

                wait_publish=0
                tzq=0
                while True:
                    try:
                        cot=await page.content()
                        if ('Product has been successfully published' in cot) or ('Listed successfully!' in cot) or '/portal/product/list/unpublished/draft' in page.url :
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},成功发布,剩余:{len(draft_list)-dj} 个产品')
                            break
                        
                        
                        if 'Cannot create product because the shop is under penalty' in cot:

                            await page.close()
                            await plw.stop()
                            close_SunBrowser(bid,self.task_id)

                            return {'code':0,'msg':'店铺受到惩罚','aff':0}

                                
                        
                        el_save_publish=page.locator('//div[text()="Are you sure to Save and Publish ?"]/../../..//span[text()="Save and Publish"]')

                        if (await el_save_publish.count())>0:
                            try:
                                await el_save_publish.click(delay=200)
                                await asyncio.sleep(1)
                            except Exception as e:
                                print(e)
                    except Exception as e:
                        print(e)
                        

                    await asyncio.sleep(1)
                    wait_publish+=1
                    tzq+=1
                    if wait_publish>21:
                        res_del_ccc=await plw_xp_del_draftpro(page,basic_info,[d_itemid])
                        aff_reset=self.ms.ExecNoQuery('update s1688pro set copyright_th=?,th_live_status=? where itemid=?',('大数据侵权','发布超时失败',str(d_pid),))
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},发布超时失败,标记删除:{aff_reset},剩余:{len(draft_list)-dj} 个产品')
                        break

                    if tzq==20:
                        el_publist=page.locator('xpath=//span[text()="Publish"]')
                        try:
                            await el_publist.click(delay=200)
                        except Exception as e:
                            print(e)

                        tzq=0
                
                await asyncio.sleep(3)
                        

            return_res={'code':0,'msg':'执行成功','aff':suc}

        except Exception as e:
            traceback.print_exc()
            logging.error(e)
            return_res={'code':-3,'msg':str(e)}

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_del_testad_pro(self):

        '''虾皮删除不达标测品'''
        basic_info=self.basic_info
        host=self.host
        dpName=self.dpName
        bid=self.bid
        country=basic_info['Country']
        rs_del=tms.ExecQuery('select itemid from ShopeeAdsPaesed where bid=? and is_del_pro=1',(bid,))
        if len(rs_del)==0:
            return_res={'code':0,'msg':'无需删除','aff':0}
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()

        url=f'https://{host}/portal/product/list/live/all?operationSortBy=recommend_v2'  
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}



        try:
            await plw_wait_xpath(page,'//div[@class="list-page-header-title"]')
            itemid_need_del=[]
            itemid_need_del_indp=[r[0] for r in rs_del]
            pro_list=await plw_xp_get_prolist(page,basic_info)
            for pitem in pro_list:
                cur_itemid=str(pitem['id'])
                if cur_itemid in itemid_need_del_indp:
                    itemid_need_del.append(cur_itemid)

            logging.info(f'店铺:《{dpName}》,{bid},在售数量:{len(pro_list)},数据库需删除:{len(itemid_need_del_indp)},实际需删除:{len(itemid_need_del)}')
            suc_del=await plw_xp_del_pros(page,basic_info,itemid_need_del)
            return_res={'code':0,'msg':'执行成功','aff':len(suc_del)}

        except Exception as e:
            traceback.print_exc()
            logging.error(e)
            return_res={'code':-3,'msg':str(e)}

        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_cj_bal_inc(self):
        '''虾皮采集Balance-Income'''

        basic_info=self.basic_info
        bid=self.bid
        dpName=self.dpName
        host=basic_info['host']
        iskj=self.iskj
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()
        t0=asyncio.create_task(plw_check_pass(page,basic_info))
        
        url=f'https://{host}/portal/finance/income?type=2&dateRange=PAST_THREE_MONTH'
        if iskj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        logging.info(f'店铺:《{dpName}》,{bid},第一步,获取《Income Details(收入详情)》...')
        #await plw_check_pass(page,basic_info,True)
        await plw_wait_xpath(page,'//div[@class="main-content"]/div[@class="section-title"]')
        msg=''
        if iskj:
            indatas=await plw_xp_get_kj_income_rpt(page,basic_info)
        else:
            indatas=await plw_xp_get_income_rpt(page,basic_info)
        if indatas:
            aff=0
            for indata in indatas:
                zds=list(indata.keys())
                paras=list(indata.values())
                aff+=self.ms.merge_into('ShopeeIncome',zds,paras,['Order_ID'],True)
            logging.info(f'店铺:《{dpName}》,{bid},成功存入 {aff} 条 Income数据')
            msg+='下载Income报表成功,'
        else:
            logging.info(f'店铺:《{dpName}》,{bid},下载Income报表失败')
            msg+='下载Income报表失败,'
        logging.info(f'店铺:《{dpName}》,{bid},第二步,获取《Balance(交易明细)》...')
        url=f'https:/{host}/portal/finance/wallet/shopeepay'
        if self.iskj==1:
            print(f'店铺:《{dpName}》,{bid},跨境店')
            url=f'https:/{host}/portal/finance/cncb-wallet'
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})
            url+='&active_tab=transaction&sw_type=withdrawal'
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        await plw_wait_xpath(page,'//div[@class="remote-component"]')

        balance_datas=await plw_xp_get_balance_rpt(page,basic_info)
        if balance_datas:
            aff=0
            for indata in balance_datas:
                zds=list(indata.keys())
                paras=list(indata.values())
                aff+=self.ms.merge_into('ShopeeMyBalance',zds,paras,['Date'],True)
            logging.info(f'店铺:《{dpName}》,{bid},成功存入 {aff} 条 Balance数据')
            msg+='下载Balance报表成功,'
        else:
            logging.info(f'店铺:《{dpName}》,{bid},下载Balance报表失败')
            msg+='下载Balance报表失败,'
        
        logging.info(f'店铺:《{dpName}》,{bid},第三步,获取《MyProduct(在售产品列表)》...')

        pro_sku_list=await plw_xp_get_pro_sku_list(page,basic_info)

        if pro_sku_list:
            aff=0
            for indata in pro_sku_list:
                zds=list(indata.keys())
                paras=list(indata.values())
                aff+=self.ms.merge_into('ShopeeMyProduct',zds,paras,['skuid'],True)
            logging.info(f'店铺:《{dpName}》,{bid},成功存入 {aff} 条 MyProduct数据')
            msg+='获取MyProduc列表成功'
        else:
            logging.info(f'店铺:《{dpName}》,{bid},获取MyProduc')
            msg+='获取MyProduc列表失败'
        
        return_res={'code':0,'msg':msg,'aff':1}
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_cj_product_overview(self):
        '''虾皮采集ProductOverview'''

        basic_info=self.basic_info
        bid=self.bid
        dpName=self.dpName
        host=basic_info['host']
        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()
        t0=asyncio.create_task(plw_check_pass(page,basic_info))
        
        url=f'https://{host}/datacenter/product/overview'
        if self.iskj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})
        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}
        
        
        #await plw_check_pass(page,basic_info,True)
        await plw_wait_xpath(page,'//p[@class="feature-section__title"]')
        msg=''
        tts=['real_time','yesterday','past7days','past30days']
        for tt in tts:
            logging.info(f'店铺:《{dpName}》,{bid},第,开始获取时间段:{tt}的《ProductOverview》...')
            indatas=await plw_xp_get_ProductOverview_rpt(page,basic_info,tt)
            if indatas:
                aff=0
                for indata in indatas:
                    zds=list(indata.keys())
                    paras=list(indata.values())
                    aff+=self.ms.merge_into('ShopeeProductOverview',zds,paras,['Date','dtype'],True)
                logging.info(f'店铺:《{dpName}》,{bid},时间段:{tt},成功存入 {aff} 条 ProductOverview数据')
                msg+='下载ProductOverview报表成功,'
            else:
                logging.info(f'店铺:《{dpName}》,{bid},时间段:{tt},下载ProductOverview报表失败')
                msg+='下载ProductOverview报表失败,'
        

        
        return_res={'code':0,'msg':msg,'aff':1}
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_manage_opt_ads(self):

        '''虾皮跨境店广告管理'''
        bid=self.bid
        bname=self.dpName
        basic_info=self.basic_info
        host=self.host
        country=self.basic_info['Country']

        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()
        t0=asyncio.create_task(plw_check_pass(page,basic_info))

        url=f'https://{host}/datacenter/product/performance'
        if self.iskj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})

        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}

        
    
        
        try:
            await plw_wait_xpath(page,'//div[@class="cell" and (text()="Product Information" or text()= "商品")]')
            ad_bb_list=await plw_xp_get_adbb(page,basic_info,'last_month',state='ongoing')
            if ad_bb_list is None:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-3,'msg':'获取广告报表失败'}
            
            ll_bb_list=await plw_xp_get_pro_performance(page,basic_info,'m')
            if ll_bb_list is None:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-3,'msg':'获取流量报表失败'}
            
            pro_list= await plw_get_xp_prolist(page,basic_info)

            if pro_list is None:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-3,'msg':'获取产品列表失败'}

            itemid_cart_map={str(llitem['id']):[llitem['add_to_cart_buyers'],llitem['uv_to_add_to_cart_rate']] for llitem in ll_bb_list}
            itemid_shopee_stock_map={str(pitem['id']):pitem['stock_detail']['total_shopee_stock'] for pitem in pro_list }
            logging.info(f'店铺:《{bname}》,{bid},广告数:{len(ad_bb_list)},加购数据:{len(itemid_cart_map.keys())},库存数据:{len(itemid_shopee_stock_map.keys())}')


            
            need_paused_count=0
            need_delpro_count=0
            suc_pause=0
            suc_del=0

            for aj,aditem in enumerate(ad_bb_list,start=1):
                cur_itemid=str(aditem['manual_product_ads']['item_id'])
                cur_campid=aditem['campaign']['campaign_id']
                cur_pname=aditem['title']
                adrpt=aditem['report']
                
                cur_random_code=None
                mat=re.search(r'.*\|(.{8})\|$',cur_pname)
                if mat:
                    cur_random_code=mat.group(1)

                if aditem['state']!='ongoing':
                    #logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告停用跳过')
                    continue

                if itemid_shopee_stock_map.get(cur_itemid,0) >0:
                    logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},有虾皮库存,跳过执行')
                    continue

                action_pause_ad=False
                action_del_pro=False
                is_jl=False
                add_to_cart_buyers=None
                uv_to_add_to_cart_rate=None
                actual_conditions=None
                standards=None

                cost=aditem['report']['cost']/100000
                impression=adrpt['impression']
                ctr=adrpt['ctr']
                click=adrpt['click']
                roas=adrpt['broad_roi']
                

                if impression>100 and ctr<0.01:
                    is_jl=True
                    action_pause_ad=True
                    action_del_pro=True
                    need_paused_count+=1
                    need_delpro_count+=1
                    standards='impression>100,CTR >= 1%'
                    actual_conditions=f'impression:{impression},ctr:{ctr*100:.2f}%'
                    ads_status='CTR不达标'


                elif itemid_cart_map.get(cur_itemid):
     
                    add_to_cart_buyers,uv_to_add_to_cart_rate=itemid_cart_map[cur_itemid]
                    cost_30day_list=OPT_Country_Condition_Map[country]['cost_range']

                    for cj in range(len(cost_30day_list)):
                        if cj < len(cost_30day_list) - 1:
                            min_cost=cost_30day_list[cj]
                            max_cost=cost_30day_list[cj+1]
                            if min_cost<=cost<max_cost and add_to_cart_buyers<(cj+1):
                                is_jl=True
                                action_pause_ad=True
                                action_del_pro=True
                                need_paused_count+=1
                                need_delpro_count+=1
                                standards=f'Expense_30合计:{min_cost}~{max_cost},add_to_cart_buyers>={cj+1}'
                                actual_conditions=f'Expense_30合计:{cost},add_to_cart_buyers:{add_to_cart_buyers}'
                                ads_status='cost加购不达标'
                                break
                        else:
                            min_cost=cost_30day_list[cj]
                            if cost>=min_cost and not roas:
                                is_jl=True
                                action_pause_ad=True
                                action_del_pro=True
                                need_paused_count+=1
                                need_delpro_count+=1
                                standards=f'Expense_30合计>={min_cost},roas>0'
                                actual_conditions=f'Expense_30合计:{cost},roas:{roas}'
                                ads_status='costROAS不达标'
                        
                    if  not action_pause_ad:

                        if (
                            (10<=click<20 and add_to_cart_buyers<1) 
                            or (20<=click<30 and add_to_cart_buyers<2)
                            or (30<=click<40 and add_to_cart_buyers<3)
                            or (click>=40 and add_to_cart_buyers<4)
                        ):
                            is_jl=True
                            action_pause_ad=True
                            action_del_pro=True
                            need_paused_count+=1
                            need_delpro_count+=1
                            standards=f''
                            actual_conditions=f'click:{click},add_to_cart_buyers:{add_to_cart_buyers}'
                            ads_status='Click加购不达标'
                         

         
                is_del_pro=0
                is_pause_ad=0
                
                if action_pause_ad:
                    res_paused_ad=await plw_xp_pause_ad(page,basic_info,[cur_campid])
                    if res_paused_ad and res_paused_ad['code']==0:
                        is_pause_ad=1
                        suc_pause+=1
                        logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告成功下架')
                    else:
                        logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告下架失败')
                

                if is_jl:
                    pdata={
                        'bid':bid,
                        'shopid':self.shopid,
                        'bname':bname,
                        'country':basic_info['Country'],
                        'sjbm':self.sjbm,
                        'yybm':self.yybm,
                        'campaign_id':str(cur_campid),
                        'itemid':cur_itemid,
                        'random_code':cur_random_code,
                        'title':cur_pname,
                        'cost':cost,
                        'add_to_cart_buyers':add_to_cart_buyers,
                        'uv_to_add_to_cart_rate':uv_to_add_to_cart_rate,
                        'impression':impression,
                        'CTR':ctr,
                        'roas':roas,
                        'standards':standards,
                        'actual_conditions':actual_conditions,
                        'ads_status':ads_status,
                        'is_pause_ad':is_pause_ad,
                        'is_del_pro':is_del_pro,
                        'click':click
                    }

                    zds=list(pdata.keys())
                    paras=list(pdata.values())

                    aff_jl=self.ms.merge_into('ShopeeOPT',zds,paras,['campaign_id'],True)
                    logging.info(f'店铺:《{bname}》,{bid},广告:{cur_campid},itemid:{cur_itemid},记录操作:{aff_jl}')


            logging.info(f'店铺:《{bname}》,{bid},需暂停:{need_paused_count},成功暂停:{suc_pause},需删除:{need_delpro_count},成功删除:{suc_del}')
            return_res={'code':0,'msg':'执行成功','aff':suc_pause}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':-3,'msg':str(e)}

            
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_manage_ml_ads(self):

        '''马来测品管理(CPC和CTR)'''
        bid=self.bid
        bname=self.dpName
        basic_info=self.basic_info
        host=self.host
        country=self.basic_info['Country']

        res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
        if not res_bbb:
            return {'code':-1,'msg':'启动浏览器失败'}
        plw,browser=res_bbb
    
        defaultContext = browser.contexts[0]
        page =await defaultContext.new_page()
        t0=asyncio.create_task(plw_check_pass(page,basic_info))

        st_time_sq8,ed_time_sq8=get_shopee_timestamp('today',8)
        url=f'https://{host}/portal/marketing/pas/index?from={st_time_sq8}&to={ed_time_sq8}&type=new_cpc_homepage&group=today'
        if self.iskj==1:
            url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})

        await plw_repeat_goto(page,url)
        sss=await plw_check_login(page,basic_info)
        if not sss:
            await page.close()
            await plw.stop()
            close_SunBrowser(bid,self.task_id)
            return {'code':-2,'msg':'账户登录失败'}

        
    
        
        try:
            await plw_wait_xpath(page,'//span[text()="Export Data " or text()="导出数据 "]')
            ad_bb_list=await plw_xp_get_adbb(page,basic_info,'last_month',state='ongoing')

            if ad_bb_list is None:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-3,'msg':'获取广告报表失败'}
            aff_mbb=upload_adbb(basic_info,ad_bb_list,'last_month')
            logging.info(f'店铺:《{bname}》,{bid},成功上传 {aff_mbb} 个广告报表数据')
            need_paused_count=0
            need_delpro_count=0
            suc_pause=0
            suc_del=0

            for aj,aditem in enumerate(ad_bb_list,start=1):
                cur_itemid=str(aditem['manual_product_ads']['item_id'])
                cur_campid=aditem['campaign']['campaign_id']
                cur_pname=aditem['title']
                adrpt=aditem['report']
                
                cur_random_code=None
                mat=re.search(r'.*\|(.{8})\|$',cur_pname)
                if mat:
                    cur_random_code=mat.group(1)

                if aditem['state']!='ongoing':
                    #logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告停用跳过')
                    continue

                action_pause_ad=False
                action_del_pro=False
                is_jl=False

                cost=aditem['report']['cost']/100000
                impression=adrpt['impression']
                ctr=adrpt['ctr']
                click=adrpt['click']
                roas=adrpt['broad_roi']
                

                if impression>100 and ctr<0.03:
                    is_jl=True
                    action_pause_ad=True
                    action_del_pro=True
                    need_paused_count+=1
                    need_delpro_count+=1
                    ads_status=f'impression:{impression},CTR:{ctr}<0.03'

                elif cost>=0.15:
                    is_jl=True
                    action_pause_ad=True
                    action_del_pro=True
                    need_paused_count+=1
                    need_delpro_count+=1
                    ads_status=f'Expense_30天_马来西亚:{cost}>=0.15'

                elif click>=5:
                    is_jl=True
                    action_pause_ad=True
                    action_del_pro=True
                    need_paused_count+=1
                    need_delpro_count+=1
                    ads_status=f'Expense_30天_马来西亚:{click}>=5'

                if action_pause_ad:
                    res_paused_ad=await plw_xp_pause_ad(page,basic_info,[cur_campid])
                    if res_paused_ad and res_paused_ad['code']==0:
                        suc_pause+=1
                        logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告成功下架')
                    else:
                        logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},广告下架失败')

                if action_del_pro:
                    # res_get_bb=await self.yb_get_time_graph(page,[aditem])
                    # logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告,删除前下载小时报表{res_get_bb}')
                    # if res_get_bb['code']==0:
                        res_del_pro=await plw_xp_del_pro(page,basic_info,[int(cur_itemid)])
                        if res_del_pro and res_del_pro['code']==0 and res_del_pro['data']['result'][0]['code']==0:
                            suc_del+=1
                            logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},成功删除产品')
                        else:
                            logging.info(f'店铺:《{bname}》,{bid},第 {aj} 个广告:{cur_campid},itemid:{cur_itemid},删除产品失败')


                if is_jl:
                    aff_jl=self.ms.ExecNoQuery('update S1688Pro set ml_ad_status=? where random_code=?',(ads_status,cur_random_code))
                    logging.info(f'店铺:《{bname}》,{bid},广告:{cur_campid},itemid:{cur_itemid},随机码:{cur_random_code},记录操作:{aff_jl}')


            logging.info(f'店铺:《{bname}》,{bid},需暂停:{need_paused_count},成功暂停:{suc_pause},需删除:{need_delpro_count},成功删除:{suc_del}')
            return_res={'code':0,'msg':'执行成功','aff':suc_pause}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':-3,'msg':str(e)}

            
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res

    async def yb_big_atc(self):

        '''大数据一筛~六筛ATC'''
        bid=self.bid
        bname=self.dpName
        dpName=bname
        basic_info=self.basic_info
        host=self.host
        country=basic_info['Country']
        tid=self.task_id
        shop_usage=Task_Name_dict[tid]
        cur_time=time.time()
        set_day_range=7
        zd_dc_bid=Country_Sql_Zd_Map[country]['zd_dc_bid']
        try:

            res_bbb= await connect_browser_pw(self.basic_info,self.task_id)
            if not res_bbb:
                return {'code':-1,'msg':'启动浏览器失败'}
            plw,browser=res_bbb
        
            defaultContext = browser.contexts[0]
            page =await defaultContext.new_page()
            url=f'https://{host}/portal/product-mass/import/upload'
            if self.iskj==1:
                url=add_query_parameters(url,{'cnsc_shop_id':self.shopid})


            await plw_repeat_goto(page,url)
            sss=await plw_check_login(page,basic_info)
            if not sss:
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-2,'msg':'账户登录失败'}
            await asyncio.sleep(5)


            logging.info(f'店铺:《{dpName}》,{bid},第一步,删除并标记 《{shop_usage}》产品')

            pro_bb_list=await plw_xp_get_pro_performance(page,basic_info,'m')

            if pro_bb_list is None:
                logging.info(f'店铺:《{dpName}》,{bid},获取产品列表错误,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-4,'msg':'获取流量报表错误'}
            upload_performance(basic_info,pro_bb_list,'m')
            itemid_has_atc={str(llitem['id']):llitem['add_to_cart_buyers'] for llitem in pro_bb_list if llitem['add_to_cart_buyers']>0}
            pro_list=await plw_xp_get_prolist(page,basic_info)
            if pro_list is None:
                logging.info(f'店铺:《{dpName}》,{bid},获取产品列表错误,退出')
                await page.close()
                await plw.stop()
                close_SunBrowser(bid,self.task_id)
                return {'code':-4,'msg':'获取产品列表错误'}
            logging.info(f'店铺:《{dpName}》,{bid},在售产品:{len(pro_list)},其中有加购数据:{len(itemid_has_atc.keys())}')
            itemids_need_del=[]
            itemid_rcode_map={}
            for pro in pro_list:
                p_itemid=str(pro['id'])
                p_name=pro['name']
                rcode_mat= re.search(r'.*\|(.{8})\|$',p_name)
                rcode=rcode_mat.group(1) if rcode_mat else None
                p_create_time=pro['create_time']
                if rcode:
                    itemid_rcode_map[p_itemid]=rcode
                if itemid_has_atc.get(p_itemid):
                    itemids_need_del.append(p_itemid)

                elif (cur_time-p_create_time) > set_day_range*86400:
                    itemids_need_del.append(int(p_itemid))
            if self.task_id==40:
                itemid_need_mark=set(itemid_has_atc.keys())
            else:
                itemid_need_mark=set(itemids_need_del)
            
            itemid_suc_del=await plw_xp_del_pros(page,basic_info,itemids_need_del)
            itemid_need_mark2=itemid_need_mark & set(itemid_suc_del)
            aff_mark2=0
            if itemid_need_mark2:
                wstr_mark2=','.join([f"'{itemid_mark2}'" for itemid_mark2 in itemid_need_mark2])
                aff_mark2=self.ms.ExecNoQuery(f"update ShopeeProPerformance set shop_usage='{shop_usage}' where itemid in ({wstr_mark2})")
            rcode_need_reset=[itemid_rcode_map[cc_itemid] for cc_itemid in itemid_need_mark2 if itemid_rcode_map.get(cc_itemid)]
            aff_reset_s1688pro_bid=0
            if rcode_need_reset:
                wstr_rcode_need_reset=','.join([f"'{rcode}'" for rcode in rcode_need_reset])
                aff_reset_s1688pro_bid=self.ms.ExecNoQuery(f"update S1688Pro set {zd_dc_bid}=null where random_code in ({wstr_rcode_need_reset})")

            logging.info(f'店铺:《{dpName}》,{bid},需要删除:{len(itemids_need_del)},成功删除:{len(itemid_suc_del)},需要标记:{len(itemid_need_mark)},成功标记:{aff_mark2},成功重置:{aff_reset_s1688pro_bid}')


            list_info=await plw_xp_get_list_count(page,basic_info)
            publish_limit_count= await plw_xp_get_product_count_limit(page,basic_info)
            all_count=list_info['all']
            draft_count=list_info['draft']
            can_count=publish_limit_count-all_count-draft_count
            if can_count>100:
                can_count=100

            if draft_count<40 and self.rocde_list:
                rcodes=self.rocde_list
                dcmr=await plw_get_ads_excel_pro(page,basic_info,rcodes,data_type=shop_usage)

                if dcmr!=0:

                    file_names=os.listdir(dcmr)
                    for j,file_name in enumerate(file_names,start=1):

                        file_path=os.path.join(dcmr,file_name)
                        logging.info(f'店铺:《{self.dpName}》,{self.bid},开始上传第 {j} 个文件:《{file_path}》')
                        upload_ipt=await plw_wait_xpath(page,'//input[@class="eds-file-uploader uploader eds-upload__input"]')
                        await upload_ipt.set_input_files(file_path)
                        await asyncio.sleep(5)

                    res_reports=await plw_xp_get_report(page,file_names,self.basic_info)
                    for fff_nnn,res_report in res_reports.items():
                        logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传结束')
                        rp_state='Successful'
                        rp_status=res_report['record_status']
                        suc_count=res_report['success_count']
                        handled_count=res_report['handled_count']
                        if suc_count==0:
                            rp_state='Unsuccessful'
                        if rp_status==7 or handled_count==0:
                            rp_state='Failed'
                        
                        if rp_state!='Successful':
                            logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传失败')
                        else:
                            logging.info(f'店铺:《{self.dpName}》,{self.bid},文件 《{fff_nnn}》上传成功')
                            await asyncio.sleep(1)



            await asyncio.sleep(3)
            draft_list=await plw_xp_get_draftlist(page,basic_info)

            suc_draft_rcodes=[]
            suc_draft_map={}
            
            for draft_pitem in draft_list:
                d_itemid=str(draft_pitem['id'])
                ptit=draft_pitem['name']
                rcode_mat= re.search(r'.*\|(.{8})\|$',ptit)
                rcode=rcode_mat.group(1) if rcode_mat else None
                if rcode:
                    suc_draft_map[rcode]=d_itemid
                    suc_draft_rcodes.append(rcode)
            
            if suc_draft_rcodes:
                wstr_suc_rcode=','.join([f"'{rcode}'" for rcode in suc_draft_rcodes])
                aff_draft=self.ms.ExecNoQuery(f"update S1688Pro set {zd_dc_bid}='{self.bid}' where random_code in ({wstr_suc_rcode})")
                logging.info(f'店铺:《{bname}》,{bid},草稿箱共 {len(draft_list)} 个产品,其中标记大数据:{aff_draft} 个')
            

            logging.info(f'店铺:《{bname}》,{bid},第三步,从草稿箱上架 {len(draft_list[:can_count])} 个 产品')
            
            for dj,pro_draft_list in enumerate(draft_list[:can_count],start=1):
                ptit=pro_draft_list['name']
                d_itemid=pro_draft_list['id']
                d_pid=pro_draft_list['parent_sku']
                rcode_mat= re.search(r'.*\|(.{8})\|$',ptit)
                rcode=rcode_mat.group(1) if rcode_mat else None
  

                quality_violation_result=pro_draft_list['quality_violation_result']
                if quality_violation_result>0:
                    await plw_xp_del_dfaft_and_mark(page,basic_info,d_itemid,d_pid,zd_dc_bid,'违规')
                    continue


                edit_url=f'https://{host}/portal/product/unpublished/{d_itemid}'
                await plw_repeat_goto(page,edit_url)
                sss=await plw_check_login(page,basic_info)
                if not sss:
                    # await page.close()
                    # await plw.stop()
                    # close_SunBrowser(bid,self.task_id)
                    # return {'code':-2,'msg':'账户登录失败'}
                    await asyncio.sleep(5)
                    continue
                
                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,开始发布...')
                await asyncio.sleep(3)
                el_tc=page.locator('//div[text()="Discard changes?"]/..//span[text()="Cancel"]')
                if (await el_tc.count()>0):
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,出现取消弹窗点击')
                    await el_tc.click(delay=200)
                    await asyncio.sleep(3)

                is_tc=False
                wait_lm=0
                while True:
                    try:
                        el_select_category= page.locator('xpath=//div[@class="category-select-item"]')
                        if (await el_select_category.count())>0:
                            ebtn= el_select_category.nth(0).locator('xpath=./div[@class="category-select-radio"]/div[1]')
                            await ebtn.click(delay=200)
                        await asyncio.sleep(3)

                        el_clm=page.locator('xpath=//div[@class="product-category-text"]/span[1]')
                        lmtxt=await el_clm.text_content()
                        if lmtxt !='Please set category':
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,成功选中类目')
                            break
                    except Exception as e:
                        traceback.print_exc()
                        await asyncio.sleep(2)
                    wait_lm+=1
                    if wait_lm>7:
                        is_tc=True
                        break
                if is_tc:
                    await plw_xp_del_dfaft_and_mark(page,basic_info,d_itemid,d_pid,zd_dc_bid)
                    continue

                await asyncio.sleep(5)

                el_ipt_des=page.locator('xpath=//div[@componentkey="ProductDescriptionEditor"]//textarea[1]')
                if (await el_ipt_des.count())>0:

                    des_txt=await el_ipt_des.input_value()
                    is_chinese,replace_txt=remove_chinese(des_txt)
                    if is_chinese==1:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:《{d_itemid}》,描述出现中文,需替换')
                        await el_ipt_des.fill(replace_txt)
                        await asyncio.sleep(1)



                upload_img=page.locator('xpath=//span[@class="eds-radio__label" and text()="Image"]')

                if (await upload_img.count())>0:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品,需补充尺码图')

                    rs_1688=self.ms.ExecQuery(f'select image from s1688pro where itemid=?',(d_pid,))
                    if len(rs_1688)==0 or (rs_1688 and not rs_1688[0][0]):
                        await plw_xp_del_dfaft_and_mark(page,basic_info,d_itemid,d_pid,zd_dc_bid)
                        continue
                    size_img_url=rs_1688[0][0]
                    imgcot=None
                    for _ in range(3):
                        try:
                            #img_url=size_img_url
                            img_url=f"http://155.94.192.2/cg/cjt/ImageProxy.aspx?url={size_img_url}"
                            res_img=requests.get(img_url,timeout=120)
                            if res_img.status_code==200:
                                imgcot=res_img.content
                                break
                        except Exception as e:
                            print(e)
                            await asyncio.sleep(3)
                    
                    if not imgcot:
                        continue
                        
                    os.makedirs(f'临时尺码图',exist_ok=True)
                    characters = string.ascii_letters + string.digits
                    random_code = ''.join(random.choice(characters) for _ in range(4))
                    img_path=f'临时尺码图/{random_code}_{getTimeStr()}.jpg'
                    with open(img_path,'wb') as f:
                        f.write(imgcot)
                    wait_img_ipt=0
                    is_not_sc=0
                    while True:
                        el_select_img=page.locator('xpath=//span[@class="eds-radio__label" and text()="Image"]')
                        try:
                            await el_select_img.click(delay=200)
                            await asyncio.sleep(3)
                            upload_img_ipt=page.locator('xpath=//div[@class="product-image-size-chart"]//input[@class="eds-upload__input"]')
                            if (await upload_img_ipt.count())>0:
                                break
                        except Exception as e:
                            print(e)
                        await asyncio.sleep(3)
                        wait_img_ipt+=3
                        if wait_img_ipt>60:
                            is_not_sc=1
                            break
                    if is_not_sc:
                        continue
                    

                    await upload_img_ipt.set_input_files(img_path)
                    wait_img_ipt2=0
                    is_not_sc2=0
                    while True:
                        el_img_ck=page.locator('xpath=//div[@class="image-size-chart"]//div[@class="shopee-file-upload pic"]/div[1]')

                        try:
                            cstyle=await el_img_ck.get_attribute('style')
                        except Exception as e:
                            print(e)
                            break

                        if cstyle and 'background-image: url' in cstyle:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品,成功上传尺码图')
                            os.remove(img_path)
                            break
                        await asyncio.sleep(3)
                        wait_img_ipt2+=3
                        if wait_img_ipt2>60:
                            break

                el_attribute_select_list=page.locator('xpath=//div[@class="mandatory"]/ancestor::div[@class="attribute-select-item"]')
                select_item_count=await el_attribute_select_list.count()
                if select_item_count==1:
                    await asyncio.sleep(3)
                    select_item_count=await el_attribute_select_list.count()
                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},共 {select_item_count} 项必填项,开始填写...')
                is_wait_opt_timeout=False #判断是否填写必填项超时
                for sj in range(select_item_count):
                    
                    el_row_tit=el_attribute_select_list.nth(sj).locator('xpath=.//div[@class="item-title"]/div[1]')
                    try:
                        speti_name=await el_row_tit.text_content(timeout=5000)
                    except Exception as e:
                        break
                    if 'Brand' in speti_name and 'Applicable Mobile' not in speti_name:
                        continue

                    el_ipt=el_attribute_select_list.nth(sj).locator('xpath=.//input[1]')
                    bt_ipt_count=await el_ipt.count()
                    if bt_ipt_count>0:
                        for iptjjj in range(bt_ipt_count):
                            await el_ipt.nth(iptjjj).fill('220')
                            await asyncio.sleep(1)
                        continue

                    if 'Expiry Date' in speti_name:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性是日期属性特殊处理...')
                        is_wait_opt_timeout=True
                        break

                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》,开始填写')
                    el_xl=el_attribute_select_list.nth(sj).locator('xpath=./div[1]/div[2]//div[@class="eds-select"]')
                    #需填写有效期的操作
                    el_xl_btn=el_attribute_select_list.nth(sj).locator('xpath=./div[1]/div[2]//div[@class="eds-selector__suffix"]')
                    el_xl_ipt=el_xl.locator('xpath=.//div[contains(@class,"placeholder")]')
                    if (await el_xl_ipt.count())==0:
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》已经预填写跳过...')
                        continue
                
                    is_mut=False
                    wait_opt=0
   
                    while True:
                        try:
                            await el_xl_btn.click(delay=200)
                        except Exception as e:
                            print(e)
                        el_opts=page.locator('xpath=//ul[@class="eds-dropdown-menu"]//div[@class="eds-option"]')
                        el_opts2=page.locator('xpath=//ul[@class="eds-dropdown-menu"]//div[@class="eds-option multiple"]')
                        if (await el_opts.count())>0:
                            break
                        if (await el_opts2.count())>0:
                            el_opts=el_opts2
                            is_mut=True
                            break
        
                        await asyncio.sleep(3)
                        wait_opt+=1
                        if wait_opt>10:
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性:《{speti_name}》填写超时退出')
                            is_wait_opt_timeout=True
                            break
                    
                    if is_wait_opt_timeout:
                        break
                    
                    is_select=False
                    for opj in range(await el_opts.count()):
                        el_copt=el_opts.nth(opj)
                        try:
                            el_txt=(await el_copt.text_content(timeout=10000)).lower()
                        except Exception as e:
                            print(e)
                            break
                        if el_txt.startswith('no') or el_txt.startswith('oth') or '14 years' in el_txt:
                            try:
                                await el_copt.click(delay=200)
                                is_select=True
                                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},第{sj+1}个属性,选中:<{el_txt}>,退出')
                                break
                            except Exception as e:
                                print(e)
                                
                    if not is_select:
                        try:
                            await el_opts.nth(0).click(delay=200)
                        except Exception as e:
                            print(e)
                    
                    if is_mut:

                        try:
                            await el_xl_btn.click(delay=200)
                        except Exception as e:
                            print(e)

                logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},必填项,填写完毕')
                await asyncio.sleep(1)
                if country=='马来西亚':
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},填写包裹体积...')
                    el_parcel=page.locator('xpath=//div[@data-auto-correct-key="dimension"]/div[@class="edit-row-right-full"]')
                    if (await el_parcel.count())>0:
                        el_width_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.width"]//input')
                        await el_width_ipt.fill('15')
                        await asyncio.sleep(1)
                        el_length_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.length"]//input')
                        await el_length_ipt.fill('20')
                        await asyncio.sleep(1)
                        el_high_ipt=el_parcel.locator('xpath=.//div[@data-product-edit-field-unique-id="dimension.height"]//input')
                        await el_high_ipt.fill('10')
                        await asyncio.sleep(1)
                        logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},包裹体积填写完毕')
                        await asyncio.sleep(3)

                await asyncio.sleep(2)
                el_shipping=page.locator('xpath=//div[@class="product-shipping container"]//div[@class="grid optional-item"]//div[@class="eds-switch eds-switch--close eds-switch--normal"]')
                shipping_count=await el_shipping.count()
                if shipping_count>0 and country in ['马来西亚','泰国','越南'] :

                    el_first_shipping=el_shipping.nth(0)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},选择运费')
                    try:
                        await el_first_shipping.click(delay=200)
                        await asyncio.sleep(2)
                    except Exception as e:
                        print(e)
                    el_qr_btn=page.locator('xpath=//div[contains(., "Once this channel is enabled")]//button[1]')
                    if (await el_qr_btn.count())>0:
                        try:
                            await el_qr_btn.click(delay=200)
                            await asyncio.sleep(2)
                        except Exception as e:
                            print(e)
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},成功选中第一个运费')
                await asyncio.sleep(3)

                if is_wait_opt_timeout:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},等待超时')
                    continue
                el_publist=page.locator('xpath=//span[text()="Publish"]')
                try:
                    await el_publist.click(delay=200)
                except Exception as e:
                    logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},点击publish错误')

                wait_publish=0
                tzq=0
                while True:
                    try:
                        cot=await page.content()
                        if ('Product has been successfully published' in cot) or ('Listed successfully!' in cot) or '/portal/product/list/unpublished/draft' in page.url :
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},成功发布,剩余:{len(draft_list)-dj} 个产品')
                            break
                        if 'Cannot create product because the shop is under penalty' in cot:
                            await page.close()
                            await plw.stop()
                            close_SunBrowser(bid,self.task_id)
                            return {'code':0,'msg':'店铺受到惩罚','aff':0}
                    
                        el_save_publish=page.locator('//div[text()="Are you sure to Save and Publish ?"]/../../..//span[text()="Save and Publish"]')

                        if (await el_save_publish.count())>0:
                            try:
                                await el_save_publish.click(delay=200)
                                await asyncio.sleep(1)
                            except Exception as e:
                                print(e)
                        

                        await asyncio.sleep(1)
                        wait_publish+=1
                        tzq+=1
                        if wait_publish>27:
                            await plw_xp_del_dfaft_and_mark(page,basic_info,d_itemid,d_pid,zd_dc_bid)
                            logging.info(f'店铺:《{dpName}》,{bid},第 {dj} 个草稿箱产品:{d_itemid},发布超时失败,剩余:{len(draft_list)-dj} 个产品')
                            break

                        if tzq==20:
                            el_publist=page.locator('xpath=//span[text()="Publish"]')
                            try:
                                await el_publist.click(delay=200)
                            except Exception as e:
                                print(e)

                            tzq=0
                    except Exception as e:
                        traceback.print_exc()
                    await asyncio.sleep(1)
                await asyncio.sleep(3)

            return_res={'code':0,'msg':'执行成功','aff':0}
        except Exception as e:
            traceback.print_exc()
            return_res={'code':-3,'msg':str(e)}

            
        await page.close()
        await plw.stop()
        close_SunBrowser(bid,self.task_id)
        return return_res


    def start_task(self,task_id):
        rw_name=Task_Name_dict[task_id]
        fun_name=Task_Fuc_dict[task_id]
        self.task_id=task_id
        self.rw_name=rw_name
        dpname=self.dpName
        if self.iskj:
            rs= tms.ExecQuery(f"select count(*) from taskStatus where  is_cl=0 and DATEDIFF(hour, update_time, GETDATE()) < 10 and err_msg in ('账户登录失败') and bid='{self.bid}' ")
            if rs[0][0]>0:
                logging.info(f'店铺:《{dpname}》,{self.bid} 任务:《{rw_name}》,浏览器异常,跳过任务')
                return {'code':0,'msg':'跳过任务','aff':0}

        try:
                            
            func = getattr(self, fun_name)

            if inspect.iscoroutinefunction(func):
                res=asyncio.run(func())
            else:
                res=func()

            code=res['code']
            msg=res['msg']
            if code==0:

                end_zds=['bid','task_id','task_name','bname','gname','state','err_msg']
                end_params=[self.bid,task_id,rw_name,self.dpName,self.gname,1,None]
                aff_rw=tms.merge_into('taskStatus',end_zds,end_params,['bid','task_id'],True)
                logging.info(f'店铺:《{dpname}》,{self.bid} 任务:《{rw_name}》,{msg}:{aff_rw}')
            else:
                
                err_zds=['bid','task_id','task_name','bname','gname','state','err_msg','is_cl']
                err_params=[self.bid,task_id,rw_name,self.dpName,self.gname,0,msg,0]
                self.ms.merge_into('taskStatus',err_zds,err_params,['bid','task_id'],True)
                logging.info(f'店铺:《{dpname}》,{self.bid} 任务:《{rw_name}》,{msg}')


                if task_id==6:
                    zds=['shopid','bid','BName','GroupName','userName','password','SJBM','YYBM','rw_msg']
                    paras=[self.shopid,self.bid,self.dpName,self.gname,self.userName,self.password,self.sjbm,self.yybm,msg]
                    self.ms.merge_into('ShopeeCreadTask',zds,paras,['bid'],True)

            return res
        
        except Exception as e:
            traceback.print_exc()
            close_SunBrowser(self.bid,task_id)
            err_zds=['bid','task_id','task_name','bname','gname','state','err_msg','is_cl']
            err_params=[self.bid,task_id,rw_name,self.dpName,self.gname,0,str(e),0]
            self.ms.merge_into('taskStatus',err_zds,err_params,['bid','task_id'],True)
            logging.error(f'店铺:《{dpname}》,{self.bid} 任务:《{rw_name}》,出错 => {e}')
            if task_id==6:
                zds=['shopid','bid','BName','GroupName','userName','password','SJBM','YYBM','rw_msg']
                paras=[self.shopid,self.bid,self.dpName,self.gname,self.userName,self.password,self.sjbm,self.yybm,str(e)]
                self.ms.merge_into('ShopeeCreadTask',zds,paras,['bid'],True)